I am lost actually, not sure how to explain the question.
Suppose I have three array
$name = array('mark', 'jones', 'alex');
$age = array(12, 23, 34);
$country = array('USA', 'UK', 'Canada');
What I am looking for is:
array(
0 => array(
'name' => 'mark',
'age' => 12,
'country' => 'USA'
)
1 => array(
'name' => 'jones',
'age' => 23,
'country' => 'UK'
)
2 => array(
'name' => 'alex',
'age' => 34,
'country' => 'Canada'
);
Couldn't figure out any built in PHP array function to handle it.
You could do it without any manual looping like this:
// array_map with null callback merges corresponding items from each input
$merged = array_map(null, $name, $age, $country);
// walk over the results to change array_map's numeric keys to strings
$keys = ['name', 'age', 'country'];
array_walk(
$merged,
function(&$row) { $row = array_combine(['name', 'age', 'country'], $row); }
);
print_r($merged);
You can even write it in such a way that the keys in the result are equal to the names of the variables $name
, $age
, $country
without needing to repeat yourself:
// Here "name", "age" and "country" appear only once:
$inputs = compact('name', 'age', 'country');
$merged = call_user_func_array('array_map', [null] + $inputs);
$keys = array_keys($inputs);
array_walk(
$merged,
function(&$row) use($keys) { $row = array_combine($keys, $row); }
);
However, to be frank it might be more readable (and it might even be faster) to just for
over the inputs (assuming they have the same number of items) and do it manually.
try something like this
$result = array();
foreach($name as $key => $value)
{
$result[$key] = array (
'name' => $value,
'age' => $age[$key],
'country' => $country[$key]
);
}
echo '<pre>';
print_r($result);
?>