Search code examples
phpjsonarray-push

How to manipulate an array so that it returns as json structure in PHP?


I am trying to loop through a json object and push selected values into an array.

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

';

$json_output = json_decode($json);
$pBB = array("title" => array(), "type" => array());
foreach($json_output->products as $obj){
    array_push($pBB['title']," {$obj->name}");
    array_push($pBB['type']," {$obj->type}" );

}
echo  json_encode($pBB);

the output of above code is

{
  "title": [
    " LG - 1.1 Cu. Ft. Mid-Size Microwave - Black",
    " Rocketfish In-Wall HDMI Cable"
  ],
  "type": [
    " HardGood",
    " HardGood"
  ]
}

i want to to return it as below

[
  {
     "title": "LG - 1.1 Cu. Ft. Mid-Size Microwave - Black",
     "type": "HardGood"
  },
  {
     "title": " Rocketfish In-Wall HDMI Cable",
     "type":  " HardGood"
  }
]

Any thoughts?


Solution

  • As per my comment on your question, you have used an unconventional method of organizing your products into values, where you should instead be organizing each product into separate array for each product containing its title and type. Use this instead:

    $json_output = json_decode($json);
    $pBB = array();
    foreach($json_output->products as $obj){
        $pBB[] = array(
            'title' => " {$obj->name}", // Not sure why you're using " {$obj->name}" but I preserved it
            'type' => " {$obj->type}", // You could just use $obj->type directly
        );
    }
    echo  json_encode(array_values($pBB));