简体   繁体   English

PHP foreach循环不适用于嵌套数组

[英]PHP foreach loop not working on an a nested array

I have no idea why this isn't working. 我不知道为什么这不起作用。 I've tried everything. 我已经尝试了一切。 I'm sure I'm missing something. 我确定我想念什么。

Here's the array: 这是数组:

$userList = array('first_name'=>array('John','Jane'), 'last_name'=>array('Smith','Doe'));

The for loop works, I do get a proper output: for循环有效,我确实获得了正确的输出:

$usercount = count($userList);  
for($i=0; $i < $usercount; $i++) {  
echo $userList['first_name'][$i];  
}

But this foreach loop doesn't: 但是,此foreach循环不会:

foreach($userList as $user) {  
echo $user['first_name'];  
echo $user['last_name'];  
}

What should I do? 我该怎么办? What's wrong with the code? 代码有什么问题?

There are no first_name or last_name keys in your inner arrays. 内部数组中没有first_namelast_name键。 What $user contains is array('John','Jane') respectively array('Smith','Doe') . $user包含的是array('John','Jane')array('Smith','Doe')

What you probably want though is a structure like: 但是,您可能想要的结构是:

$userList = array(
    array('first_name' => 'John', 'last_name' => 'Smith'), 
    array('first_name' => 'Jane', 'last_name' => 'Doe')
);

That allows you to use the foreach you allready have. 这使您可以使用已经拥有的foreach。

The foreach approach isn't going to give you the desired output because of the way your array is structured: 由于数组的结构方式,foreach方法不会为您提供所需的输出:

foreach($userList as $user) {
    //$user is array('John', 'Jane') on the first iteration
}

You could update your array to look like this: 您可以将数组更新为以下形式:

array(
    array('first_name' => 'John', 'last_name' => 'Smith'),
    array('first_name' => 'Jane', 'last_name' => 'Doe')
);

Your foreach loop should work with the array structured like that. 您的foreach循环应与具有这种结构的数组一起使用。

If you do print_r($userList); 如果您执行print_r($userList); the output is 输出是

Array
(
    [first_name] => Array
        (
            [0] => John
            [1] => Jane
        )

    [last_name] => Array
        (
            [0] => Smith
            [1] => Doe
        )
)

As you can see, you are storing all of the first names in one array and all of the last names in another array. 如您所见,您将所有名字存储在一个数组中,并将所有姓氏存储在另一个数组中。 I think you meant to store each user in their own array. 我认为您打算将每个用户存储在他们自己的数组中。

To do that, you need something like 为此,您需要类似

 $userList = array(array("first_name" => "John", "last_name" => "Doe"), array("first_name" => "Jane", "last_name" => "Doe"));

Now if you print_r($userList); 现在,如果您print_r($userList); it will output: 它将输出:

Array
(
    [0] => Array
        (
            [first_name] => John
            [last_name] => Doe
        )

    [1] => Array
        (
            [first_name] => Jane
            [last_name] => Doe
        )

)

Which your foreach statement should correctly iterate through. 您的foreach语句应正确地迭代哪个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM