遍历数组内的STD类对象

时间:2018-07-06 09:53:21

标签: php arrays

我已经使用Ajax通过FormData发送了一个包含数据的数组。 我先对其进行json编码,然后再发送通过,然后在PHP端将其解码回。

我的问题是:"Trying to get property 'ID' of non-object""Illegal string offset ID"

这很奇怪,因为我的数组就像:

 array(7) {
 [0]=>
 object(stdClass)#779 (2) {
    ["ID"]=>
    string(1) "1"
    ["Value"]=>
    string(19) "Onbeperkt helpdesk."
 }
 [1]=>
 object(stdClass)#780 (2) {
    ["ID"]=>
    string(1) "2"
    ["Value"]=>
    string(43) "Een direct aanspreekpunt voor al uw vragen."
 }
 [2]=>
 object(stdClass)#781 (2) {
    ["ID"]=>
    string(1) "3"
    ["Value"]=>
    string(20) "Een stabiel netwerk."
 }
 [3]=>
 object(stdClass)#782 (2) {
    ["ID"]=>
    string(1) "4"
    ["Value"]=>
    string(43) "Uw belangrijke gegevens optimaal beveiligd."
 }
}

我尝试遍历数组的方式:

 $voordelen = json_decode($_POST['voordelen']);
                        echo var_dump($voordelen);
                        for ($i = 0; $i < count($voordelen); $i++) {
                            foreach ($voordelen[$i] as $key => $item) {
                                $voorArray = array(
                                    "id" => $item->ID,
                                    "item" => $item->Value,
                                    "content_id" => $content->id // variable from code not shown here.
                                );
                            }
                        }

我也尝试过:

                            for ($i = 0; $i < count($voordelen); $i++) {
                            foreach ($voordelen[$i] as $item) {
                                $voorArray = array(
                                    "id" => $item->ID,
                                    "item" => $item->Value,
                                    "content_id" => $content->id // Variable from code not shown here.
                                );
                            }
                        }

我还尝试使用$var['value']代替$var->value

但是现在我很茫然。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

因为$voordelen已经是一个数组,所以仅遍历它有什么问题:

$voordelen = json_decode($_POST['voordelen']);

foreach( $voordelen as $item )
{
    $voorArray = array(
        "id"         => $item->ID,
        "item"       => $item->Value,
        "content_id" => $content->id 
    );

    // Do something with $voorArray here.
}

答案 1 :(得分:2)

我认为您正在做一个额外的循环,您是否尝试过:

foreach ($voordelen as $item) {
    $voorArray = array(
        "id" => $item->ID,
        "item" => $item->Value,
        "content_id" => $content->id // Variable from code not shown here.
    );
    var_dump($voorArray);
}