0

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.

1
  • PHP has a lot of built-in functions, but you'll find yourself writing your own just as much (or more). Commented Jul 10, 2014 at 14:36

2 Answers 2

2

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);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.