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?

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.