Reputation: 13
Array_merge and array_merge_recursive are not working as desired, creating more indexes instead of pushing the arrays together and retaining the index number. See below for input/desired output:
Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
)
)
Desired Output:
Array (
[0] => array("string1","string4","string7"),
[1] => array("string2","string5","string8"),
[2] => array("string3","string6","string9")
)
EDIT:
Perhaps not the best example; I want to achieve the same results but with an unequal number of keys in each nested array. See below for a better example:
<?php
$array = Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
),
[3] => array(
[0] => "string10",
[1] => "string11",
[2] => "string12"
)
);
$output=array();
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array();
}
for($i=0;$i<count($array);$i++){
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array_push($output[$j],$column_values[$i][$j]);
}
}
?>
But when I do this, I get the correct number of keys in my $output array, but they all contain a bool(false). Any help?
This is the desired output:
Array (
[0] => array("string1","string4","string7","string10"),
[1] => array("string2","string5","string8","string11"),
[2] => array("string3","string6","string9","string12")
)
Upvotes: 0
Views: 130
Reputation: 13
Got it. Last loop should simply array_push($output[$j],$column_values[$i][$j]);
instead of trying to set the variable $output[$j] = array_push(Yadda,yadda)
.
Upvotes: 0
Reputation: 14931
This is for your 'second' situation:
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"),array("string10","string11","string12"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<=count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
Upvotes: 0
Reputation: 14931
This is to make an array just for this structure of array, so you may change the code depanding on your needs ...
<pre>
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
</pre>
Upvotes: 1