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
FartMachine4U
1151 gold badge3 silver badges10 bronze badges
-
$originalArray[$val] is outright wrong. you can't use your values as keys... $val is ALREADY the value.Marc B– Marc B2014年01月23日 15:10:06 +00:00Commented Jan 23, 2014 at 15:10
-
Marc B - you CAN use your own keys as values.FartMachine4U– FartMachine4U2014年01月23日 15:16:45 +00:00Commented 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.Marc B– Marc B2014年01月23日 15:19:58 +00:00Commented Jan 23, 2014 at 15:19
-
[Convert flat, associative array into indexed 2d array with associative rows [duplicate]](stackoverflow.com/q/74595808/2943403)mickmackusa– mickmackusa ♦2024年10月30日 12:34:12 +00:00Commented Oct 30, 2024 at 12:34
3 Answers 3
It's even simpler than that:
$new_array[] = array("name" => $key, "status" => $val);
answered Jan 23, 2014 at 15:08
Explosion Pills
193k56 gold badges341 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
hsz
153k63 gold badges269 silver badges320 bronze badges
Comments
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
Srijith Vijayamohan
9256 silver badges18 bronze badges