我正在尝试循环json对象并使用键将所选值推送到数组中。
$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);
以下是我得到的错误
<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}
如果我按下没有按键的值,它就能正常工作,而且我会低于输出
[" LG - 1.1 Cu. Ft. Mid-Size Microwave - Black"," Rocketfish In-Wall HDMI Cable"]
任何想法,提前致谢!
答案 0 :(得分:6)
$pBB['title']
是null
,因为您尚未对其进行定义。
更改
$pBB = array();
到
$pBB = array("title" => array(), "type" => array());
更新
$pBB = array();
foreach($json_output->products as $obj){
$pBB[] = array(
"title" => $obj->name,
"type" => $obj->type
);
}
echo json_encode($pBB);