简体   繁体   English

PHP数组到json格式

[英]PHP Array to json formatting

I'm trying to get my PHP arrays to format in the way I need them to. 我正在尝试以我需要的方式格式化我的PHP数组。

Here's what the outcome is: 结果如下:

 [
  {
    "Ryan": {
      "id": "5c7c9ef16f667",
      "quantity": "1"
    }
  },
  {
    "Paul": {
      "id": "5c7d888e14233",
      "quantity": "2"
    }
  }
]

Here's what my desired outcome is: 这是我期望的结果:

{
  "Ryan": {
    "id": "5c7c9ef16f667",
    "quantity": "as"
  },
  "Paul": {
    "id": "5c7d888e14233",
    "quantity": "asd"
  }
}

And here's my code: 这是我的代码:

$tools = array();
foreach ($tool_names as $key=>$value) {
    $item = Item::find_by_name($value);
    $tools[] = array($item['name'] => ["id" => $item['id'], "quantity" => $tool_quantities[$key]]);
}

json_encode($tools);

Any ideas for how I can change my code to make my array work like that? 关于如何更改代码以使数组像这样工作的任何想法?

You need to mutate your main array rather than pushing new arrays into it: 您需要更改主数组,而不是将新数组推入主数组:

$tools = array();
foreach ($tool_names as $key=>$value) {
    $item = Item::find_by_name($value);
    $tools[$item['name']] = array("id" => $item['id'], "quantity" => $tool_quantities[$key]);
}

json_encode($tools);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM