[英]foreach loop not working with single result
I have got the following array stored in the variable $details
: 我将以下数组存储在变量$details
:
[formats] => Array (
[format] => Array (
[0] => Array (
[formatId] => 1
[code] => High
[price] => Array (
[0] => 0.00
[1] => 0.00
[2] => 0.00
[3] => 0.00
[4] => 0.00 ) )
[1] => Array (
[formatId] => 2
[code] => Med
[price] => Array (
[0] => 0.00
[1] => 0.00
[2] => 0.00
[3] => 0.00
[4] => 0.00 ) )
) )
and I use the following code to loop trough this array 我使用以下代码循环遍历此数组
<? foreach ($details['formats']['format'] as $format)
{
echo $format['code'];
}
?>
Which works fine, but then, sometimes there is only one result in the array and then it looks like this: 效果很好,但是有时数组中只有一个结果,然后看起来像这样:
[formats] => Array (
[format] => Array (
[formatId] => 1
[code] => High
[price] => Array (
[0] => 0.00
[1] => 0.00
[2] => 0.00
[3] => 0.00
[4] => 0.00 )
) )
Unfortunally my for each loop does not work then, because it is only a single array. 不幸的是,我的for每个循环然后无法正常工作,因为它只是一个数组。 How can this be solved? 如何解决呢? I cannot change the array. 我无法更改数组。
I can use while or for loops if that is required, but I have no idea how 如果需要,我可以使用while或for循环,但是我不知道如何
A very crude method of approaching the problem would be to just fold an 'if' around it; 解决该问题的一种非常粗略的方法是在其周围加上一个“ if”。
<?
if (isset($details['formats']['format'][0])){
foreach ($details['formats']['format'] as $format)
{
echo $format['code'];
}
} else {
echo $details['formats']['format']['code'];
}
?>
This only works if the result array is consistant and it will always return [0] on multiple results. 这仅在结果数组一致时才有效,并且在多个结果上始终返回[0]。
This should work as well. 这也应该起作用。
if ( is_array($details['formats']['format']) && array_key_exists("code", $details['formats']['format']) ) {
echo $details['formats']['format']['code'];
} else if ( is_array( $details['formats']['format'] ) {
foreach ($details['formats']['format'] as $format)
{
echo $format['code'];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.