du131642
2014-11-06 19:20
浏览 29
已采纳

如何操作数组使其在PHP中作为json结构返回?

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

  • drngnh708353 2014-11-06 19:27
    最佳回答

    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));
    
    评论
    解决 无用
    打赏 举报
查看更多回答(4条)

相关推荐 更多相似问题