PHP Json 响应格式


PHP Json response formatting

我有以下脚本返回 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"
    }
  ],

任何建议将不胜感激。谢谢

您只希望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']
    )
);