duanqun9740 2014-11-06 08:52
浏览 177
已采纳

array_push()期望参数1是使用键的array_push数组

I am trying to loop a json object and push selected values into array using keys.

$json = ' { "from": 1, "to": 2, "total": 2, "currentPage": 1, "totalPages": 1, "queryTime": "0.004", "totalTime": "0.020", "partial": false, "canonicalUrl": "/v1/products(offers.type=deal_of_the_day)?format=json&apiKey=946n9vuhdkgeyz2qx2dpxd54","products": [ { "sku": 5998225, "productId": 1219180376135, "name": "LG - 1.1 Cu. Ft. Mid-Size Microwave - Black", "source": "bestbuy", "type": "HardGood", "startDate": "2014-07-06","new": false, "active": true, "lowPriceGuarantee": true, "activeUpdateDate": "2014-11-03T19:43:46", "regularPrice": 124.99, "salePrice": 99.99, "onSale": true},{ "sku": 2634897, "productId": 1218343205770, "name": "Rocketfish In-Wall HDMI Cable", "source": "bestbuy", "type": "HardGood", "startDate": "2011-08-14", "new": false, "active": true,"lowPriceGuarantee": false, "activeUpdateDate": "2014-11-03T18:03:02", "regularPrice": 29.99, "salePrice": 24.99, "onSale": true } ] }';

$json_output = json_decode($json);
$pBB = array();
foreach($json_output->products as $obj){
    array_push($pBB['title']," {$obj->name}" );
    array_push($pBB['type']," {$obj->type}" );
    //array_push($pBB," {$obj->name}" );  without key works fine
}
echo  json_encode($pBB);

and below is the error i am getting

<br />
<b>Warning</b>:  array_push() expects parameter 1 to be array, null given on line <b>6</b><br />
<br />
<b>Warning</b>:  array_push() expects parameter 1 to be array, null given on line <b>6</b><br />
{"title":null}

If i push the values without keys it works and i get below output

[" LG - 1.1 Cu. Ft. Mid-Size Microwave - Black"," Rocketfish In-Wall HDMI Cable"]

Any thoughts , Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dry9192 2014-11-06 08:53
    关注

    $pBB['title'] is null because you haven't defined it yet.

    Change

    $pBB = array();
    

    to

    $pBB = array("title" => array(), "type" => array());
    

    Update:

    $pBB = array();
    foreach($json_output->products as $obj){
        $pBB[] = array(
            "title" => $obj->name,
            "type" => $obj->type
        );
    }
    echo json_encode($pBB);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部