Jertyu
Jertyu

Reputation: 115

PHP Array to json formatting

I'm trying to get my PHP arrays to format in the way I need them to.

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?

Upvotes: 1

Views: 36

Answers (1)

scrowler
scrowler

Reputation: 24406

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);

Upvotes: 2

Related Questions