I have an array like this:
[apple] => 11
[pear] => 5
[banana] => 3
[cucumber] => 2
[tomatoes] => 8
I would like to create multi-dimensional array like this:
[randomArrayName1]
[apple] => 11
[banana] => 3
[tomatoes] => 8
[randomArrayName2]
[pears] => 5
[cucumber] => 2
I wrote this below but it is not working and I have no clue how to make it do: what I need it to do
$quantity = array();
foreach($fruit as $key => $value) {
$quantity = Finder($key);
}
randomArrayName1
and randomArrayName2
will be generated depending on Finder()
function's result. Depending on that result I want fruit array to be created as a second dimension array.
Solution: The problem was that the function I wrote that created names like randomArrayName1, randomArrayName2... was in fact a XML function. Therefore, result of this function was not an array, it was XML simple object. This caused problem on creating multidimensional array. Once I implemented the code below it converted SimpleXML to Array and code worked fine. $type is SimpleXML array $out is result array
foreach ( (array) $type as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
You can use array_reduce
. It takes three arguments, an initial array to operate on, a function which should operate on each element (which in turn requires two arguments, $carry
, which is a variable that gets passed through to the function each time through the return statement, and $item
, which is the array item being operated on) and finally an "initial" value for $carry
within the function, which in this case is going to be our multidimensional array that gets eventually returned.
This is an example where the Finder
function returns a key based on whether the value of the items in the array is odd or even, and sorts the values accordingly.
Note that we are operating on the array_keys
of fruits, so that we have access to both key and value inside our reducer.
<?php
$fruit = ['apple' => 11, 'pear' => 5, 'banana' => 3, 'cucumber' => 2, 'tomatoes' => 8];
function Finder($fruit) {
return $fruit % 2 == 0 ? 'even' : 'odd';
}
$multi = array_reduce(array_keys($fruit), function($carry, $item) use ($fruit) {
$val = $fruit[$item];
$carry[Finder($val)][$item] = $val;
return $carry;
}, []);
var_dump($multi);
/* // output
array(2) {
["odd"]=>
array(3) {
["apple"]=>
int(11)
["pear"]=>
int(5)
["banana"]=>
int(3)
}
["even"]=>
array(2) {
["cucumber"]=>
int(2)
["tomatoes"]=>
int(8)
}
}
*/
You need to create the new index or access it if it has already been created and then create another element under that with the existing key and assign the value:
$quantity = array();
foreach($fruit as $key => $value) {
$quantity[Finder($key)][$key] = $value;
}
This is assuming that Finder()
is returning a string like randomArrayName1
.