tags:

views:

72

answers:

3

Hello what is the easiest way to change this array to 1D array, i can do that using for loop or foreach, but i'm curious to check if there is an easier way. THANKS

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
        )

    [2] => Array
        (
            [id] => 3
        )
)
+2  A: 
$output_ar = array_map('array_shift', $input_ar);

The array_shift() function grabs the first key/val pair out of an array and returns the value, so applying it to each of the arrays in your top-level array, and combining the results, will result in a 1-d list of the id's.

If your arrays actually have more info than just the id field in them, then you'd probably want to define a function that specifically pulls out whatever field(s) you want and returns those, and then use that function with array_map.

Amber
This doesn't work for me, just returns empty array entries.
Psytronic
Apparently `next()` behaves weirdly inside `array_map()`. I've changed it to `array_shift()` instead, which I've verified works.
Amber
that worked perfect for me :P thanks buddy .. that what i was searching for :P
From.ME.to.YOU
This looks expensive
Gordon
Seconding Gordon's comment.
salathe
A: 

This will retrieve all the values and put them into a new Array.

// Initializing the Array
$arr0 ['id'] = 1;
$arr1 ['id'] = 2;
$arr2 ['id'] = 3;

$arr[0] = $arr0;
$arr[1] = $arr1;
$arr[2] = $arr2;


// Processing
$resultarray = array();
for ($i = 0; $i < count($arr); $i++){
  $resultarray = array_merge(array_values($arr[$i]),$resultarray);
}

// Test Output
print_r ($resultarray);
Thariama
+2  A: 

Array walk will change the original array though, so if you need a separate array, copy it first, or choose an alternative method.

function reducer($e, $i, $p){
    $e = $e[$p];
}

array_walk($array, 'reducer', "id");

This function is reusable though, as you can change "id" to any other key, or numeric value (I believe) and it will do the same thing upon that array.

Psytronic
`array_map` is an near equivalent of `array_walk` except that it returns a new array instead of modifying the original in-place.
Amber
It's not, array_map accepts multiple array inputs, and the callback will use them as it's parameters, you can't define a custom value like in array_walk. Well that's how I'm reading the documentation anyway. :)
Psytronic