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?
$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);