Alladin Alladin - 2 months ago 6
PHP Question

PHP Convert Nested Array Format

I have the following array with 2 elements:

$attribute_metric = array(2)
{
[0]=>
array(2) {
[0]=>
string(5) "white"
[1]=>
string(6) " Black"
}
[1]=>
array(3) {
[0]=>
string(1) "S"
[1]=>
string(2) " L"
[2]=>
string(2) " M"
}
}


and I want to concatenate its elements in a way where I get one array that has 6 elements in which every element should look like this

[option_value] => Array(
[0] => Array(
[value] => white
)

[1] => Array(
[value] => S
)
)


I have tried the following but I still can't get close to what I want to achieve:

$final_attribute_metric = array();
foreach ($attribute_metric[0] as $first_attribute) {
foreach ($attribute_metric[1] as $second_attribute) {
$final_attribute_metric[] = [$first_attribute,$second_attribute];
}
}

Answer

I'm not sure what exactly you're trying to come up with... but if you're trying to concat every array-of-size to each array-of-color.. then you can do the following...

$new = [];
foreach( $attribute_metric[0] as $colors ) {

  foreach( $attribute_metric[1] as $size ) {
     array_push( [ ['value'=>$color],['value'=>$size] ] );     
  }

}

The result should be ...

SixElementsArr = [

  0 => [
         0 => ['value'=>'white']
         1 => ['value'=>'S']
       ]
...//so on
]