迭代多维数组
问题描述
我正在尝试获取项目 ID,然后是该项目 ID 中的所有 option_name/option_values.所以我最终得到了 ID:123,颜色:蓝色,尺寸:6.ID:456,颜色:黄色,尺寸:8.但是我得到了正确的项目 ID,但是 option_name/option_value 没有正确通过, 要么是空白,要么只是一个随机字母.
这是我的代码不起作用,
基本上,你在循环 $item
数组,它看起来像这样:
因此在第一次迭代时,$option
将是 123
,尝试访问 '123'['option_name']
将发出一个警告.你真正想做的是:
这就是为什么你的代码没有产生想要的结果.
如果子数组并不总是将 1
作为键,请尝试:
这是获取所有选项(无论有多少)的最通用方法
但是看到您的选项数组看起来都具有数字索引,您也可以试试这个:
您可以将 for
循环替换为:
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. However I am getting the correct item ID, but the option_name/option_value isn't coming through correctly, either blank or just one random letter.
Here's my code that doesn't work,
Where $itemlist
looks like this:
Array ( [1] => Array ( [ID] => 123 [QTY] => 1 [MODEL] => sdfsd [IMAGE] => [1] => Array ( [option_name] => Color [option_value] => Blue [option_price] => 0.0000 ) [2] => Array ( [option_name] => Size [option_value] => 6 [option_price] => 0.0000 ) [price] => 0 ) [2] => Array ( [ID] => 456 [QTY] => 0 [MODEL] => gsdfgd [IMAGE] => [1] => Array ( [option_name] => Color [option_value] => Yellow [option_price] => 0.0000 ) [2] => Array ( [option_name] => Size [option_value] => 8 [option_price] => 0.0000 ) [price] => 0 ) )
Basically, you're looping over the $item
array, which looks like this:
So on the first iteration, $option
will be 123
, trying to access '123'['option_name']
will issue a warning. What you actually wanted to do is this:
That's why your code doesn't produce the desired result.
If the sub-array doesn't always have 1
as a key, try:
Here's the most generic approach to get all options (irrespective of how many)
But seeing as your options arrays look like they all have numeric indexes, you could just as well try this:
You could replace the for
loop with:
这篇关于迭代多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!