从数组中获取值时获取不正确的值

时间:2015-02-21 09:19:14

标签: php arrays for-loop multidimensional-array foreach

我需要从数组中获取值,为此我尝试引用此处给出的代码stackoverflow

我拥有的数组是

Array
(
    [success] => 1
    [products] => Array
        (
            [0] => Array
                (
                    [id] => 405
                    [name] => GOLD CHID
                    [categories] => Array
                        (
                            [0] => 39
                            [1] => 59
                        )
                )

            [1] => Array
                (
                    [id] => 404
                    [name] => KASHMIRI
                    [categories] => Array
                        (
                            [0] => 39
                            [1] => 59
                        )
                )

            [2] => Array
                (
                    [id] => 403
                    [name] => ENVELOPE BOX
                    [categories] => Array
                        (
                            [0] => 0
                            [1] => 39
                            [2] => 59
                        )
                )
        )
)

我用来获取数组的代码是

if (!empty($array)) 
    {
        foreach ($array['products'] as $product) 
            {
                echo $product['id'];
                echo "<br>";
                echo $product['name'];
                echo "<br>";

                    if(isset($product['categories']))
                        {
                            foreach($product['categories'] as $category)
                            echo $category['0'];
                            echo "<br>";
                            echo $category['1'];
                            echo "<br>";
                        }
            } 
    }

我正在设置id和name的正确值,但是我没有得到$category['0']$category['1']

的正确结果

我得到的结果是

405
GOLD CHID
35
9

404
KASHMIRI
35
9

403
ENVELOPE BOX
35
9

谁能告诉我哪里出错了?

2 个答案:

答案 0 :(得分:2)

你的问题源于几个问题。

  • 首先,您不要将第二个foreach循环包裹在大括号中
  • 其次,当您的代码不期望时,您正在迭代这些类别。

您的代码:

foreach($product['categories'] as $category)
echo $category['0'];
echo "<br>";
echo $category['1'];
echo "<br>";

有效:

foreach($product['categories'] as $category) {
    echo $category['0'];
}
echo "<br>";
echo $category['1'];
echo "<br>";

在每个类别上循环,在每个类别中打印第一个字符(35),然后在最后一个类别(9)中打印第二个字符。

将其更改为以下内容:

foreach($product['categories'] as $category) {
    echo $category;
    echo "<br>";
}

答案 1 :(得分:0)

更改此

foreach($product['categories'] as $category)
{
echo $category['0'];
echo "<br>";
echo $category['1'];
echo "<br>";
}

到这个

foreach($product['categories'] as $category)
{
 echo $category;
 echo "<br>";
 echo $category;
 echo "<br>";
}

因为在您的代码$category[0]中将输出35中的第0个元素。和$ category将给出实际值