Home > Mobile >  How to insert key value pair in an existing array object using php/laravel?
How to insert key value pair in an existing array object using php/laravel?

Time:09-22

My Code:

$finalArray = json_encode($loanTypeCount);

Output:

[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]

Desired Output:

[{"name":"Salary","y":6, "selected": true},{"name":"Emergency","y":1, "selected": true}]

Inserted "selected": true key value pair. What is the way to do it in laravel/php?

CodePudding user response:

If it's a Collection instance, you can do it with map()

$loanTypeCount->map(function($loan) {
    $loan->selected = true;
    return $loan;
});

CodePudding user response:

Based on N69S' solution, here an example starting with a JSON encoded string instead of a collection instance and ending with a modified one.

$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';

$arr = collect(json_decode($json, true))
    ->map(function ($item, $key) {
        $item['selected'] = true;

        return $item;
    })
    ->toJson();

CodePudding user response:

Simple solution with pure php:

$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';

$obj=json_decode($json);
$obj[0]->selected = true;
$obj[1]->selected = true;

$newJson = json_encode($obj);
//[{"name":"Salary","y":"6","selected":true},{"name":"Emergency","y":"1","selected":true}]

Alternatively with foreach:

$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';

foreach($obj=json_decode($json) as $key => $item){
  $obj[$key]->selected = true;
}

$newJson = json_encode($obj);
//[{"name":"Salary","y":"6","selected":true},{"name":"Emergency","y":"1","selected":true}]
  • Related