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?
-
You are creating an array of objects which you must convert to an object. This answer may help - stackoverflow.com/questions/19874555/…Anurag Srivastava– Anurag Srivastava2019年03月04日 22:44:19 +00:00Commented Mar 4, 2019 at 22:44
1 Answer 1
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);
answered Mar 4, 2019 at 22:44
scrowler
24.4k10 gold badges67 silver badges99 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jertyu
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.
lang-php