iterating through multi dimensional arrays

前端 未结 3 1060
不知归路
不知归路 2020-12-19 17:32

I am trying to get the item id, and then all option_name/option_values within that item id. So I end up with, ID: 123, Color: Blue, Size: 6. ID: 456, Color: Yellow, Size: 8.

3条回答
  •  旧巷少年郎
    2020-12-19 17:43

    This is because your array contains the POSSIBILITY of those keys existing, not guaranteed. There's a few different approaches you could take, such as checking if the key is numeric (seems only numeric keys have the correct array of keys set). But since i dont know your dataset, probably the best universal method is to change your code to check if the key's are set, before trying to use them. So..

    foreach($itemlist as $item) {
    
     foreach($item as $key => $value) {
    
          if(is_array($value) && array_key_exists('option_name', $value) {
    
               //--- Your option array is available in here via $value['option_x']
    
          }
    
     }
    
    }
    

提交回复
热议问题