0

i have a Two fields 1. allowances which is contain this data

{"medical":"600","transport":"350","food":"900"}

and another one 2. house rent which is contain this data

2550.00

now i want to get a result in third column like this

{"medical":"600","transport":"350","food":"900","house_rent":"2550.00"}

so far i tried this

$allowances=json_decode($salary->allowances);
$house_rent = array('House Rent' => $salary->house_rent);
$allowances_logs=array_push($allowances,$house_rent);
$salary->allowances_logs = $allowances_logs;

but it gives me following error"array_push() expects parameter 1 to be array, object given". Help me achieve this result. Any help will be appreciated

1
  • Look into Eloquent's $casts, so you don't have to JSON encode/decode the database value - Laravel will handle that for you. Commented Nov 23, 2019 at 15:17

3 Answers 3

1

First, add true as second argument to json_decode(), and you will retrieve the results as an array instead of an object.

Second, with the two arrays, do:

$merged = array_merge($arr1, $arr2);
Sign up to request clarification or add additional context in comments.

Comments

0

true Add second argument in json_decode(), so you can see below example

$mainArr = json_decode('{"medical":"600","transport":"350","food":"900"}',true);
$house_rent = array('House Rent' => 2550.00);
$printArr = array_merge($mainArr, $house_rent);
print_r(json_encode($printArr));

Output

{"medical":"600","transport":"350","food":"900","House Rent":2550}

Comments

0

First convert your json to array. You can do this with json_decode php function.

json_decode function convert your json to object or associative array. First argument on this function is the json string being decoded. When is second argument are TRUE, returned objects will be converted into associative arrays.

$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);

Output - Array ( [medical] => 600 [transport] => 350 [food] => 900 )

Now you can add new item to your array.

$testArr['house_rent'] = '2550.00';

Your array now look like this.

Array ([medical] => 600 [transport] => 350 [food] => 900 [house_rent] => 2500.00)

At the end you convert your array to json. For this you can use php json_encode function.

$testJson = json_encode($testArr);

Full Example

$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);

$testArr['house_rent'] = '2500.00';

$testJson = json_encode($testArr);
echo $testJson;

Comments

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.