简体   繁体   English

PHP foreach嵌套循环不接受数组的一部分

[英]PHP foreach nested loop not accepting portion of array

When I try to extract the user id from my array I get the error: 当我尝试从数组中提取用户ID时,出现错误:

[31-May-2016 21:10:00 America/New_York] PHP Warning: Invalid argument supplied for foreach() in filename.php line 24 [31-May-2016 21:10:00 America / New_York] PHP警告:在filename.php第24行中为foreach()提供了无效的参数

Here is the code: 这是代码:

$users = $lists->users;
foreach($users as $user) 
{
    $true_id = $user->id;
    foreach ($true_id as $i => $id) 
    {
        if (empty($friends->ids) or !in_array($id, $friends->ids)) 
        {
            $ret = $toa->post('friendships/create', array('user_id' => $id));
        }
    }
}

you need to assign the objects as arrays. 您需要将对象分配为数组。

$users = (array) $lists->users;
foreach ($users as $user) {
    $true_id = (array) $user->id;
    foreach ($true_id as $i => $id) {
        if (empty($friends->ids) || in_array($id, $friends->ids) === false) {
            $ret = $toa->post('friendships/create', array('user_id' => $id));
        }
    }
}

You are trying to iterate on $user->id , however, this does not seem to be an iterable object. 您试图在$user->id上进行迭代,但是,这似乎不是一个可迭代的对象。

Just access the scalar field id without any nested loop: 只需访问标量字段id而无需任何嵌套循环:

$users = (array) $lists->users;
foreach ($users as $user) {
    if (empty($friends->ids) || in_array($user->id, $friends->ids) === false) {
        $ret = $toa->post('friendships/create', array('user_id' => $user->id));
    }
}

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

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