By inverse I mean from the following:
$my_array = array(
"header" => array(
0 => "Header 1",
1 => "Header 2"
),
"paragraph" => array(
0 => "Paragraph 1",
1 => "Paragraph 2"
)
);
to this:
$my_new_array = array(
0 => array(
"header" => "Header 1",
"paragraph" => "Paragraph 1"
),
1 => array(
"header" => "Header 2",
"paragraph" => "Paragraph 2"
)
);
I know that I can do this:
$my_new_array = array();
foreach ( $my_array["header"] as $key => $header ){
if ( !is_array( $my_new_array[ $key ] ) ){
$my_new_array[ $key ] = array();
}
$my_new_array[ $key ]["header"] = $header;
}
foreach ( $my_array["paragraph"] as $key => $paragraph ){
$my_new_array[ $key ]["paragraph"] = $paragraph;
}
But I was wondering if there was a quick PHP function to do this or a more optimal way. I couldn't find any such function in the PHP function directory, and i can't think of a more optimal way!
Cheers
This would work without using concrete keys:
$new = array();
foreach ($my_array as $key => $values) {
foreach ($values as $idx => $value) {
$new[$idx][$key] = $value;
}
}
$my_new_array = array();
array_walk($my_array, function($innerArray, $key) use (&$my_new_array) {
foreach ($innerArray as $index => $val) {
$my_new_array[$index][$key] = $val;
}
});
...is the best I can come up with, although it's basically the same thing written differently. It does have the advantage of being more dynamic as the key names are not specified explicitly.
No built-in function to do this unfortunately, but since the existing answers seem to favor foreach
I 'm entering this candidate into the race with maximum array_walk
ness on the agenda:
$result = array();
array_walk($array, function($rows, $propKey) use (&$result) {
array_walk($rows, function($val, $row) use($propKey, &$result) {
$result[$row][$propKey] = $val;
});
});