I want to flatten multidimensional array to single dimensional so I use array_reduce() to get it done.
But struck in this place.
$array = array
(
1 => array
(
0 => 1,
1 => 'a'
),
2 => array
(
0 => 2,
1 => 'b'
)
)
Code :
$key = 1;
$array_reduced = array_reduce( $array,function(&$result, $item){
$result[] = $item[$key];
return $result;
});
print_r($array_reduced);
Output Should be :
Array
(
[0] => a
[1] => b
)
Which shows Undefined variable: key in this line $result[] = $item[$key];
If I replace the $item[$key] to $item[1] its working.
How to use $key in array_reduce().
Well your problem is simply that the variable $key is out of scope in the closure function. So you could either use the keyword global (which isn't the nicest) or use(). So I would recommend you to use use() like this:
array_reduce($array, function(&$result, $item)use($key){ //<-- See use
$result[] = $item[$key];
$key++; //Don't forget to increment your variable
return $result;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With