【问题标题】:Getting content from two stdObject array从两个 stdObject 数组中获取内容
【发布时间】:2013-07-24 19:09:17
【问题描述】:
[responseheader] => Object (
    Array ( 
        [0] =>  Object ( 
            [id] => id_1 
            [name] => abc 
        )
        [1] => Object ( 
            [id] => id_2 
            [name] => xyz 
        ) 
    ) 
) 
[response] => Object ( 
    [id_1] => Object ( 
        [content] => Array ( 
            [0] => content_1 
            ) 
        ) 
    [id_2] => Object ( 
        [content] => Array ( 
            [0] => content_2
        )
    )
)

以上2个对象responseheaderresponse都在一个对象(header)之下。

在上述结构中,response 的顺序与responseheader 中的顺序相同。(即,id_2 总是在id_1 之后)

我想为responseheader 中的每个idresponse 获取content。我将迭代responseheader 对象。

我可以遍历response 并逐步在responseheader 中添加另一个属性(例如dummy)来存储content,但是有没有更好、更快的方法?

【问题讨论】:

    标签: php arrays object stdclass


    【解决方案1】:

    这应该可以解决问题。

    $result = array();
    //loop through responseheader array
    foreach($data['responseheader'] as $row)
    {
        //if the id exists in the response array add it to the result array
        if(array_key_exists($row['id'], $data['response'])) {
            $result[] = $data['response'][$row['id']]['content'][0];
        }
    }
    print_r($result);
    

    如果响应的内容可能包含多个内容,您必须将其循环到:

    foreach($data['response'][$row['id']]['content'] as $content) {
        $result[] = $content;
    }
    

    【讨论】:

    • 谢谢。每个id_* 对象下只会有一个content。有什么办法可以将内容添加到responseheader 中的相应id?其中还有许多其他字段,因此我将迭代responseheader
    • 是的。只需将其添加到 $row 而不是结果数组即可。
    猜你喜欢
    • 2012-03-17
    • 2014-07-31
    • 2018-02-11
    • 2017-06-15
    • 2018-01-25
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多