PHP Json响应格式化

时间:2016-03-15 18:21:16

标签: php json

我有以下脚本返回json响应。

$response["customer_creds"] =array(array('customer_names'=>$user['name'], 'customer_email' => $user['email'], 'customer_id' => $user['customer_id'], 'customer_type' => $user['customer_type'], 'rating' => $user['rating']));

上面的脚本返回:

"customer_creds": [
    {
      "customer_names": "John Doe",
      "customer_email": "example@example.com",
      "customer_id": "123456",
      "customer_type": "1",
      "rating": "4"
    }
  ],

现在我希望我的json将customer_type作为对象返回。("customer_type": [1],

我在同一个脚本上尝试了json解码和编码,但似乎没有任何效果。有没有解决方法呢?在稍后阶段,我想让我的json返回多个客户类型。最终的回答应该是这样的:

"customer_creds": [
  {
      "customer_names": "John Doe",
      "customer_email": "example@example.com",
      "customer_id": "123456",
      "customer_type": [1,2,3],
      "rating": "4"
    }
  ],

任何建议都将受到高度赞赏。感谢

1 个答案:

答案 0 :(得分:2)

您只希望customer_type是一个值数组,而不只是一个值?

$response["customer_creds"] = array(
    array(
        'customer_names' => $user['name'], 
        'customer_email' => $user['email'], 
        'customer_id' => $user['customer_id'], 
        'customer_type' => array($user['customer_type']), // Just wrap it with array()
        'rating' => $user['rating']
    )
);