1

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?

Jertyu
  • 105
  • 8
  • You are creating an array of objects which you must convert to an object. This answer may help - https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript/49247635 – Anurag Srivastava Mar 04 '19 at 22:44

1 Answers1

2

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);
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • 1
    Thank you! I thought I might have needed to do something like that but I wasn't sure exactly how to do it... I will accept your answer once I am able to. – Jertyu Mar 04 '19 at 22:47