Alko Alko - 2 days ago 7
JSON Question

Php append new key to an existing array

I have an existing JSON array:

stdClass Object
(
[set] => Array
(
[0] => stdClass Object
(
[name] => agenda
)

[1] => stdClass Object
(
[name] => first aid
)
)

)


I need to add a new key to it, so the final json result is something like this:

set: [{
name: 'agenda',
value: 'Agenda'
}, {
code: 'first aid',
value: 'First Aid'
}],


This is what I've done so far:

$result = array();
foreach ($data->set as $k => $row) {
$result['name'][$k] = $row->name;
$result['value'][$k] = ucwords($row->name);
}


but I have ended up with:

Array
(
[name] => Array
(
[0] => agenda
[1] => aid kit

)
[value] => Array
(
[0] => Agenda
[0] => First Aid
)
)


How can I merge the above so the name and value keys are in pair rather then being separate.

Answer

Update $row directly to modify your existing $data:

foreach ($data->set as $row) {
    $row->value = ucwords($row->name);
}

To do it the way you are attempting:

$result = $data;
foreach ($data->set as $k => $row) {
    $result->set[$k]->value = ucwords($row->name);
}

Notice, $row is an object.

Comments