PHP - Foreach对象

时间:2016-03-06 21:06:49

标签: php arrays api twitter laravel-5

我试图在我的视图中遍历此数据对象。但是,我收到以下错误:Trying to get property of non-object。这是我第一次真正遇到渲染数组/对象的问题......也许这只是周日的情况......但是我无法得到这个{{1输出。救命? 编辑: 我添加了键/值" search_type"到返回的数组 - 我认为这可能导致问题?

foreach

返回:

$results = $twitter->get("users/search", ["q" => $term, "count" => $num, "include_entities" => 'false']);
$results['search_type'] = 'people';

FOREACH:

{
    "0": {
        "id": 1108217089,
        "id_str": "1108217089",
        "name": "Marketing",
        "screen_name": "SocialMedia246",
        "location": "Canada",
        "description": "Marketing|PR|Brand Consultant.Lover of Music|Fashion & life.A dynamic young entrepreneur with an unconventional out of the box approach to marketing & business.",
    },
    "1": {
        ...
    },
    search_type: "people"

最小化vardump,用于search_results:

@foreach ($search_results as $result => $profile)
    <div class="large-3 columns">               
        {{ $profile->id }}
    </div>
@endforeach

3 个答案:

答案 0 :(得分:1)

我相信你没有正确阅读文件。

请尝试以下循环:

<?php
    $sInFile  = 'in3.json';
    $sOutFile = 'out3.json';

    $sRaw     = file_get_contents( $sInFile );
    $aData    = json_decode( $sRaw, 1 );

    // $aData = array();
    // $aTmp                  = array();
    // $aTmp[ 'id' ]          = '1108217089';
    // $aTmp[ 'id_str' ]      = '1108217089';
    // $aTmp[ 'name' ]        = 'Marketing';
    // $aTmp[ 'screen_name' ] = 'SocialMedia246';
    // $aTmp[ 'location' ]    = 'Canada';
    // $aTmp[ 'description' ] = 'Marketing';
    // $aData[] = ( object ) $aTmp;

    // $aTmp                  = array();
    // $aTmp[ 'id' ]          = '1108217089';
    // $aTmp[ 'id_str' ]      = '1108217089';
    // $aTmp[ 'name' ]        = 'Marketing';
    // $aTmp[ 'screen_name' ] = 'SocialMedia246';
    // $aTmp[ 'location' ]    = 'Canada';
    // $aTmp[ 'description' ] = 'Marketing';
    // $aData[] = ( object ) $aTmp;


    foreach ($aData as $result => $profile)
    {
        var_dump( $result );
        var_dump( $profile );
        var_dump( $profile->id );
    }
    var_dump( $aData );

    $sNewJson = json_encode( $aData );
    var_dump( $sNewJson );
    file_put_contents( $sOutFile, $sNewJson );

?>

答案 1 :(得分:1)

您的问题是您尝试从字符串id获取people属性。

答案 2 :(得分:0)

好的,所以@potfur在评论中提出了一个很好的观点。我没有添加密钥Job job = new Job(someName, someDay, somePriority); jobs.add(job); ,而是将结果保存到search_type数组中。救我麻烦和头痛。感谢你们的帮助。这是我应该接受的错误。

people

现在是vardump(这更有意义):

$results['people'] = $twitter->get("users/search", ["q" => $term, "count" => $num, "include_entities" => 'false']);