I have the following 2 arrays:
Array 1
(
[0] => Speed
[1] => Grade
[2] => Speed
[3] => Grade
[4] => Speed
[5] => Grade
[6] => Grade
[7] => Speed
[8] => Size
)
Array 2
(
[0] => 5200 rpm
[1] => Red
[2] => 7200 rpm
[3] => Blue
[4] => 8900 rpm
[5] => Green
[6] => Purple
[7] => 10000 rpm
[8] => Big
)
The values are matching each other. For example: Speed - 5200 rpm , Grade - Red and so forth.
I need to make the above like the following :
$collection = array(
"Speed" => array (
5200 rpm,
7200 rpm,
8900 rpm,
10000 rpm
),
"Grade" => array (
Red,
Blue,
Green,
Purple
),
"Size" => array (
Big
)
);
It needs to make an array for each label and store the necessary values into the array. I have tried merging and combining and looping. I am going wrong somewhere.
Can someone please help me out.
Try this code
$array_1 = array('Speed','Grade','Speed','Grade','Speed','Grade','Grade','Speed','Size');
$array_2 = array('5200 rpm','Red','7200 rpm','Blue','8900 rpm','Green','Purple','10000 rpm','Big');
foreach($array_1 as $key=>$elm){
$finalArray[$elm][] = $array_2[$key];
}
echo("<pre>");
print_r($finalArray);
echo("</pre>");
With foreach you can use label for create new array multi-dimensional! Is very easy. I hope I have helped you, for any questions, please comment
Save array 1 as $description
and array 2 as $value
.
You need to get the array values of both arrays, using:
$description = array_values($description);
And then you can use array_combine.
$combined = array_combine($description, $value);
Related (for array values) Convert an associative array to a simple array of its values in php
PHP Docs for array_combine
here.
EDIT
I read the question again and I see that index are the same for array 1 and array 2
$collection = array();
foreach (array1 as $key => $value){
$collection[$value][] = $array2[$key];
}