Reputation: 616
I have the following Array in hand. I have to iterate the following array in order that it will create another array with an output of 0th index of every sub-array on the 0th index of new array and so on.
Current Array
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
Desired Output
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => 2
)
[2] => Array
(
[0] => 3
[1] => 3
[2] => 3
)
)
Upvotes: 2
Views: 50
Reputation: 3561
$input = [
0 => [1, 2, 3],
1 => [1, 2, 3],
2 => [1, 2, 3]
];
$output = [
array_column($input, 0),
array_column($input, 1),
array_column($input, 2)
];
print_r($output);
// Output:
//
// Array
// (
// [0] => Array
// (
// [0] => 1
// [1] => 1
// [2] => 1
// )
// [1] => Array
// (
// [0] => 2
// [1] => 2
// [2] => 2
// )
// [2] => Array
// (
// [0] => 3
// [1] => 3
// [2] => 3
// )
// )
Upvotes: 0
Reputation: 234
That's not allot of info to work with...so, something like:
$newArray = [];
foreach($topArray as $idxTop => $valTop){
if(is_array($valTop)){($newArray[] = $valTop[0];}
}
Upvotes: 0
Reputation: 212522
For PHP versions >= 5.5.0 you have the array_column() function:
$newArray = array_column(
$oldArray,
0
);
For earlier versions of PHP, you can use array_map()
$column = 0;
$newArray = array_map(
function ($value) use ($column) {
return $value[$column];
},
$oldArray
);
Upvotes: 5