[英]what am i doing wrong with this array and foreach?
I have two arrays, where I can get from using $result[0] or $result[1]. 我有两个数组,我可以使用$ result [0]或$ result [1]。
I've done a print_r($results[0])
and a print_r($result[1])
. 我做了一个print_r($results[0])
和一个print_r($result[1])
。 they both give me the two different arrays which I want. 他们都给了我想要的两个不同的阵列。
However, I'm not able to get any of my information if I do this 但是,如果我这样做,我无法获得任何信息
foreach($results[0] as $result){
echo $result['data']['id'];
}
I want to be able to differentiate the two arrays, so I want to be able to get information from the two. 我希望能够区分这两个数组,所以我希望能够从这两个数组中获取信息。
I have done a json_decode on $results as well. 我也在$ results上做了一个json_decode。
If someone can help me out here, that'll be great! 如果有人可以帮助我,这将是伟大的! thanks 谢谢
EDIT: 编辑:
Array
(
[nonsense] => Array
(
[more] => information
[less] => less stuff
)
[data] => Array
(
[0] => Array
(
[id] => some id
)
[1] => Array
(
[eh] => some eh
)
)
)
Array
(
[more stuff] => Array
(
[more] => information
[less] => less stuff
)
[more data] => Array
(
[0] => Array
(
[freshstuff] => some id
)
)
)
In your example $result['data']['id']
doesn't exist. 在您的示例中, $result['data']['id']
不存在。 id
is inside yet another array. id
在另一个数组中。
foreach
is not useful in this situation because the data isn't uniform. foreach
在这种情况下foreach
,因为数据不统一。 When you loop through $results[0]
you get the nonsense
key on the first iteration and the data
key on the second iteration. 当你遍历$results[0]
你会在第一次迭代时获得nonsense
键,在第二次迭代时获得data
键。 Furthermore, the nonsense
key is an array of key/value pairs, while the data
key is an array of arrays of key/value pairs. 此外, nonsense
键是键/值对的数组,而data
键是键/值对的数组的数组。
$results[0]
and $results[1]
seem uniform, but they contain different keys. $results[0]
和$results[1]
似乎是统一的,但它们包含不同的键。
echo $results[0]['data'][0]['id'], "<br>\n";
echo $results[0]['data'][1]['eh'], "<br>\n";
echo $results[1]['more data'][0]['freshstuff'], "<br>\n";
Update 更新
foreach() doesn't work with this kind of array. foreach()不适用于这种数组。 array_walk_recurisive() is generally a good choice in this situation. 在这种情况下, array_walk_recurisive()通常是一个不错的选择。
<pre>
<?php
$results = array(
array(
'nonsense' => array(
'more' => 'information',
'less' => 'less stuff'
),
'data' => array(
array('id' => 'some id'),
array('eh' => 'some eh')
)
),
array(
'more stuff' => array(
'more' => 'information',
'less' => 'less stuff'
),
'more data' => array(
array('freshstuff' => 'some id'))
)
);
function test_print($item, $key)
{
echo "$key: $item\n";
}
array_walk_recursive($results, 'test_print');
?>
</pre>
displays 显示器
more: information
less: less stuff
id: some id
eh: some eh
more: information
less: less stuff
freshstuff: some id
Depending on your needs, you may also find some of the other array functions useful. 根据您的需要,您可能还会发现其他一些有用的数组函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.