This question already has an answer here:
How to get array like below format using php, i want to get simillar structure as of defined below.
My Array is like below order,
$customarray =
Array
(
[0] => Finish1
[1] => Hook1
[2] => Material1
[3] => Mounting1
)
Array
(
[0] => Finish2
[1] => Hook2
[2] => Material2
[3] => Mounting2
)
Array
(
[0] => Finish3
[1] => Hook3
[2] => Material3
[3] => Mounting3
)
Resultant array would like to below format,
$resultantArray =
Array
(
[0] => Finish1
[1] => Finish2
[2] => Finish3
)
Array
(
[0] => Hook1
[1] => Hook2
[2] => Hook3
)
Array
(
[0] => Material1
[1] => Material2
[2] => Material3
)
Array
(
[0] => Mounting1
[1] => Mounting2
[2] => Mounting3
)
Any help would be appericiated,
Thanks.
</div>
Hope this will help you out..
<?php
ini_set('display_errors', 1);
$customarray = array(
Array
(
0 => "Finish1",
1 => "Hook1",
2 => "Material1",
3 => "Mounting1"
),
Array
(
0 => "Finish2",
1 => "Hook2",
2 => "Material2",
3 => "Mounting2"
),
Array
(
0 => "Finish3",
1 => "Hook3",
2 => "Material3",
3 => "Mounting3",
)
);
$result=array();
for($x=0;$x<count($customarray);$x++)
{
for($y=0;$y<count($customarray[$x]);$y++)
{
$result[$y][$x]=$customarray[$x][$y];//here we are flipping values
}
}
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => Finish1
[1] => Finish2
[2] => Finish3
)
[1] => Array
(
[0] => Hook1
[1] => Hook2
[2] => Hook3
)
[2] => Array
(
[0] => Material1
[1] => Material2
[2] => Material3
)
[3] => Array
(
[0] => Mounting1
[1] => Mounting2
[2] => Mounting3
)
)
This will do:
$a = []; //Your array
/*
$a = array(
Array
(
0 => "Finish1",
1 => "Hook1",
2 => "Material1",
3 => "Mounting1"
),
Array
(
0 => "Finish2"
*/
$output = []; //output array
foreach($a as $key => $innerArr){
foreach($innerArr as $val){
$valKey = preg_replace('/[0-9]+/', '', $val);
$output[$valKey][] = $val;
}
}
You could do this with some array_map
and call_user_func_arrray
magic
$a = [
['11', '12', '13'],
['21', '22', '23'],
['31', '32', '33'],
['41', '42', '43'],
];
$b = call_user_func_array('array_map', array_merge((array)function() {
return func_get_args();
}, $a));
the following should be easier to understand, as it works without array_merge
$b = call_user_func('array_map', function() {
return func_get_args();
}, ...$a);
or even easier
$b = array_map(function() {
return func_get_args();
}, ...$a);
and if you know the internals of array_map, you could even shorten it a little bit more by just passing null as callback function
$b = array_map(null, ...$a);