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]);
}
aksu
5,2365 gold badges26 silver badges39 bronze badges
asked Jan 23, 2014 at 15:06
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);
answered Jan 23, 2014 at 15:08
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
 );
}
answered Jan 23, 2014 at 15:09

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);
}
answered Jan 23, 2014 at 15:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.