Multidimensional array - how to get specific values ​​from a submatrix

I have the following array structure:

 Array ([0] => Array ([product_option_id] => 236 [option_id] => 14 [name] => Masura S [type] => select [option_value] => Array ([0] => Array ([product_option_value_id ] => 33 [option_value_id] => 53 [name] => Alb [price] => [price_prefix] => +) [1] => Array ([product_option_value_id] => 35 [option_value_id] => 55 [name] => Rosu [price] => [price_prefix] => +)) [required] => 0) [1] => Array ([product_option_id] => 237 [option_id] => 15 [name] => Masura M [ type] => select [option_value] => Array ([0] => Array ([product_option_value_id] => 34 [option_value_id] => 58 [name] => Rosu [price] => [price_prefix] => +)) [required] => 0)) 

I get lost trying to display all the [name] values ​​from this array.

What I'm trying to do is fill in the form with a drop-down list based on the first level [name] (for example, [name] => Masura S ), and then select the second drop-down list with the second level [name] (for example, [name] => Alb ).

I would appreciate if you have pointers ...

+6
source share
4 answers

You can fill in the first selection as follows:

 <select> <?php $c=count($array); for ( $i=0; $i < $c; $i++) { ?> <option><?php echo $array[$i]['name'];?></option> <?php } ?> </select> 

2nd select:

 <select> <?php for ( $i=0; $i < $c; $i++) { $c2=count($array[$i]); for ($j=0;$j<$c2;$j++){ ?> <option><?php echo $array[$i][$j]['name'];?></option> <?php }} ?> </select> 
+7
source

I would split the names into separate arrays like this, after that it should be easy to populate the drop-down lists as needed:

 $product_names = $option_names = array(); foreach ($products as $index => $product) { $product_names[$index] = $product['name']; foreach ($product['option_value'] as $option) { $option_names[$index][] = $option['name']; } } 

If you need a product name for array index 0, you must use $ product_names [0] (string), and the option names for this product can be found from $ option_names [0] (array).

The code above does not care about the existing identifier, so if you need them for the form, you need to expand the code a bit.

+4
source

You will need to use a recursive function
here is an example

 function recursion($array) { foreach ($array as $key => $value) { echo $value; if (is_array($value)) $this->recursion($value); } } recursion($array); 
+3
source

Try the following:

 $name = array_column($array, 'name'); 
+2
source

Source: https://habr.com/ru/post/890327/


All Articles