0

I have this array ($originalArray):

Array ( 
  [c] => 1 
  [d] => 2 
  [e] => 1
  [a] => 1 
)

and would like to convert it/create another a multidimensional which would look like:

Array ( 
  [0] => Array ( [name] => a [status] => 1 ) 
  [1] => Array ( [name] => c [status] => 1 )
  [2] => Array ( [name] => d [status] => 2 )
  [3] => Array ( [name] => e [status] => 1 ) 
)

Something like this I am thinking:

$new_array = array();
foreach ($originalArray as $key=>$val)
    {
    $new_array[] = array('name'=>$originalArray[$val],'status'=>$originalArray[$key]);
}
4
  • $originalArray[$val] is outright wrong. you can't use your values as keys... $val is ALREADY the value. Commented Jan 23, 2014 at 15:10
  • Marc B - you CAN use your own keys as values. Commented Jan 23, 2014 at 15:16
  • yes, but only if those keys actually exist in the array. the above code is pointless, unless the array's build such that all keys = values. Commented Jan 23, 2014 at 15:19
  • [Convert flat, associative array into indexed 2d array with associative rows [duplicate]](stackoverflow.com/q/74595808/2943403) Commented Oct 30, 2024 at 12:34

3 Answers 3

1

It's even simpler than that:

$new_array[] = array("name" => $key, "status" => $val);
Sign up to request clarification or add additional context in comments.

Comments

1

Try with:

$input  = array('c' => 1, 'd' => 2, 'e' => 1, 'a' => 1);
$output = array();

foreach ($input as $name => $status) {
  $output[] = array(
    'name'   => $name,
    'status' => $status
  );
}

Comments

1

Your logic is right. May reduce the code by using $key, $value variables you get from the loop.

$new_array = array();
foreach ($originalArray as $key=>$val)
{
  $new_array[] = array('name'=>$val,'status'=>$key);
}

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.