2

I have the following array (contents retrieved from a DB):

array (size=4)
  0 => 
    array (size=2)
      'number' => string 'one' (length=3)
      'name' => string 'Billy' (length=5)
  1 => 
    array (size=2)
      'number' => string 'two' (length=3)
      'name' => string 'Mariah' (length=6)
  2 => 
    array (size=2)
      'number' => string 'three' (length=5)
      'name' => string 'Cindy' (length=5)
  3 => 
    array (size=2)
      'number' => string 'four' (length=4)
      'name' => string 'Daniel' (length=6)

I need to create an array as follows:

$info = array('one' => 'Billy', 'two' => 'Mariah', 'three' => 'Cindy', 'four' => 'Daniel');

I used a foreach loop to construct the desired array:

$info = array();
foreach ($result as $row) {
    $info[] = array($row['number'] => $row['name']);
}

and a var_dump() gives me this instead:

array (size=4)
  0 => 
    array (size=1)
      'one' => string 'Billy' (length=5)
  1 => 
    array (size=1)
      'two' => string 'Mariah' (length=6)
  2 => 
    array (size=1)
      'three' => string 'Cindy' (length=5)
  3 => 
    array (size=1)
      'four' => string 'Daniel' (length=6)

How can I achieve the desired array in PHP? Thanks for your help in advance.

0

2 Answers 2

5

You were close.

$info = array();
foreach ($result as $row) {
    $info[$row['number']] =$row['name'];
}
Sign up to request clarification or add additional context in comments.

Comments

0

With PHP >= 5.5.0 it's much easier:

$info = array_column($result, 'name', 'number');

Or use the PHP Implementation of array_column()

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.