Well, I have this array $city
:
[2] => Array
(
[0] => Array
(
[0] => fr
[1] => paris
[2] => a8
)
[1] => 0
[2] => 116729
)
[3] => Array
(
[0] => Array
(
[0] => fr
[1] => marseille
[2] => b8
)
[1] => 0
[2] => 12898
)
[4] => Array
(
[0] => Array
(
[0] => fr
[1] => lyon
[2] => b9
)
[1] => 0
[2] => 8608
)
And so on... I'm trying to transform it to :
[2] => Array
(
[0] => fr
[1] => paris
[2] => 0
[3] => 116729
)
[3] => Array
(
[0] => fr
[1] => marseille
[2] => 0
[3] => 12898
)
[4] => Array
(
[0] => fr
[1] => lyon
[2] => 0
[3] => 8608
)
And here's how i do it :
foreach ($city as $key => $value){
$city[$key][0] = $city[$key][0][0];
array_splice( $city[$key], 1, 0, $city[$key][0][1] );
}
But the issue here is that the result array :
[2] => Array
(
[0] => fr
[1] => r
[2] => 0
[5] => 0
)
[3] => Array
(
[0] => fr
[1] => r
[2] => 0
[5] => 0
)
[4] => Array
(
[0] => fr
[1] => r
[2] => 0
[5] => 0
)
What is the error in my code and can I fix it?
You can use array_map
instead of foreach
:
$result = array_map(
function ($v) { return array_merge(array_slice($v[0], 0, 2), array_slice($v, 1)); },
$array
);
Try this
foreach($city as $key => $value) {
$city[$key] = [
$value[0][0], //fr
$value[0][1], //lyon
$value[1], //0
$value[2], //8608
];
}
After you do:
$city[$key][0] = $city[$key][0][0];
you can't reference the original $city[$key][0]
because you've replaced it. The solution is to save it in a variable first:
foreach ($city as $key => &$value){
$subarray = $value[0];
$value[0] = $subarray[0];
array_splice($value, 1, 0, $subarray[1] );
}
I've also used a reference to avoid having to repeat $city[$key]
in the loop.
Here you go (provided that your array is called $new
in the example below):
foreach ($item as $derp) {
if (is_array($derp)) {
foreach ($derp as $derrrrrr) {
$d[$i][] = $derrrrrr;
}
} else {
$d[$i][] = $derp;
}
}
$i++;
}
?>
Array
(
[0] => Array
(
[0] => fr
[1] => paris
[2] => a8
[3] => 0
[4] => 11678
)
[1] => Array
(
[0] => fr
[1] => paris
[2] => a8
[3] => 0
[4] => 11678
)
[2] => Array
(
[0] => fr
[1] => paris
[2] => a8
[3] => 0
[4] => 11678
)
)
Use the below to ignore the index[2] in the first multi-dimensional array.
$d = array();
$i = 0;
foreach ($new as $item) {
foreach ($item as $derp) {
if (is_array($derp)) {
foreach ($derp as $key => $derrrrrr) {
if ($key !== 2) {
$d[$i][] = $derrrrrr;
}
}
} else {
$d[$i][] = $derp;
}
}
$i++;
}