How to solve array push problem in laravel - php

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

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);

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}

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;

Related

How can I parse/extract from a string in PHP? Specifically something between quotes

I have a string like this
{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}
How do I get for example, the content inside value to a variable? And I would want to be able to get it for every item with value in there. There will be several that come from a form in a single string.
This is the response from a form that stores the whole string in a string. Kinda wish it was an array but this is what i'm working with.
Your string is actually a JSON value. To get the data out of it, you must first json_decode it to an array (or object). If you choose an array, you can then use array_column to get all the 'value' values:
$json = '{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}';
$array = json_decode($json, true);
print_r(array_column($array, 'value'));
Output:
Array (
[0] => moon7
[1] => Second Choice
)
Demo on 3v4l.org

php variable converting to JSON object

I want to make an array of json objects having the structure as follows:
{
"client-mac": "0C:D2:B5:68:73:24",
"client-dbm": "-82",
"clientManuf": "unknown"
}
I am using following php code to get this result:
$clientMac = $clients->{'client-mac'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'};
$clientManuf = $clients->{'client-manuf'};
$jsonObject = array('client-mac' => $clientMac,
'client-dbm' => $clientStrength,
'clientManuf' => $clientManuf);
$jsonString = json_encode($jsonObject);
The problem is I am getting following json string:
{"client-mac":{
"0":"0C:D2:B5:68:73:24"
},
"client-dbm":{
"0":"-82"
},
"clientManuf":{"0":"Unknown"}
}
Why I am getting those extra keys as "0"? And how can I get my desired output? Thank you in advance :)
Apparently your source data has one more nested level with one key/value pair.
You could use reset on them to just pick the first value from that:
array('client-mac' => reset($clientMac),
'client-dbm' => reset($clientStrength),
'clientManuf' => reset($clientManuf));
That's because $clientMac, $clientStrength and $clientManuf are objects, not literal strings. You have to change the first three lines in the following way,
$clientMac = $clients->{'client-mac'}->{'0'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'}->{'0'};
$clientManuf = $clients->{'client-manuf'}->{'0'};
...

types (integer, Boolean,..) in JSON by using JSON_encode

I have an array similar to :
[0] => stdClass Object
(
[name] => John
[id] => 1
[pass] => 0
)
The array is returned by a sql query. Now I need to use json_encode and I want the id to be integer and pass Boolean, but they get string types after json_encode. How can I do it with the correct datatypes in json_encode?
You could loop through the array, casting each value with the key of pass to a boolean and each id to an integer like so:
<?php
foreach ($results as $result) {
$result->id = (int) $result->id;
$result->pass = (bool) $result->pass;
}
For the type conversions, you can iterate over the list first and cast the relevant properties:
foreach($data as $d)
{
$d->id = (int)$d->id;
$d->pass = (bool)$d->pass;
}
For the string conversion issue; the 2nd argument of json_encode() is options (a bitmask). The available options are listed here. The relevant option in your case is JSON_NUMERIC_CHECK, which will prevent your numbers from being converted to strings in the resulting JSON:
$json = json_encode($data, JSON_NUMERIC_CHECK);
id is integer. to make pass boolean set it as boolean (using true, false) or cast it to boolean:
$obj->pass = (bool)$obj->pass;

PHP json_decode thrown an error for validate json string

I have following error
Notice: Trying to get property of non-object in action.php
while posted json has validated (by jsonLint.com validation).
Here is my json string:
[
{
"eTGid": "1",
"eTid": "34",
"evrakGelisTarihi": "12/12/2013",
"evrakKonu": "Sertifika denemesi",
"evrakKurumID": "1047",
"evrakCikisTarihi": "13/12/2013",
"evrakCikisSayisi": "313213213213",
"aciklamaBolumu": "açıklayıcı notlar",
"gelenEvrakTarihi": "30/12/2013",
"gelenEvrakSayisi": "3132321",
"gelenEvrakEtakipNo": "987654",
"bagliIlaclar": "[\"0\",\"[{\\\"ilacID\\\":\\\"744\\\",\\\"ilacPN\\\":\\\"asdasd2132\\\",\\\"ilacSKT\\\":\\\"12/12/2013\\\"}]\"]",
"bagliFirmalar": "[\"0\",\"[{\\\"firmaID\\\":\\\"1047\\\"}]\"]",
"": "[\"0\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"asdasda\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"2\\\",\\\"ilacIhracADI\\\":\\\"ABFADER\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"10\\\"}]\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"ASDAWW\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"191\\\",\\\"ilacIhracADI\\\":\\\"ABFADEX\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"9\\\"}]\"]",
"bagliMakbuzlar": "[\"0\",\"987654»12/12/2013»3213213\"]",
"kurumIcimi": "hayir"
}
]
and my php code is:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj->{'eTGid'});
Where did I go wrong?
After suggestions:
My Json string has arrived to the serverside (php) as an array (between brackets).
Array has only one element (member) that it is our json string (object)
Handle the arrays first element and assign it to a php object and deal with it.
$gelenJsonVerisi = $_POST['yeniEvrak'];
$yeniEvrakObjArray = json_decode($gelenJsonVerisi,TRUE);
$yeniEvrakObj = $yeniEvrakObjArray[0];
exit($yeniEvrakObj['eTGid']); // one of sample value
Thank you
The JSON string shows an array, that contains a single object. access the data like so:
$yeniEvrakObj = json_decode($gelenJsonVerisi);
echo $yeniEvrakObj[0]->eTGid;
If you're sure there's but 1 object inside that array, you could try:
$yeniEvrakObj = json_decode(
substr($gelenJsonVerisi,1,-1)
);
Which chops off the leading and terminating brackets. This implies no leading of trailing whitespace, so trim the string first.
check codepad. As you can see, the json_decode call returns the data as an array containing an object:
Array
(
[0] => stdClass Object
(
[eTGid] => 1
[eTid] => 34
[evrakGelisTarihi] => 12/12/2013
[evrakKonu] => Sertifika denemesi
[evrakKurumID] => 1047
[evrakCikisTarihi] => 13/12/2013
[evrakCikisSayisi] => 313213213213
)
)
It's not json_decode throwing the error, it's when you try to access the resulting array. Yes, that's right, array. Your JSON value is this:
[ { ... } ]
^ array ^
So you need to access the result like:
$yeniEvrakObj[0]->eTGid
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
The problem is the way you're trying to access to the decoded object, as it is inside an array.
Your code should be:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
Edit: Thanks for the comments on this answer that made me see I was mistaken

Referencing a dynamic associative array position

I'm requesting data from an online source which I then decode into json StdClass objects (using php). Once I've done this I have the following (see below). I'm trying to extract the elements in 'otherstuff' by doing echo $response->stuff->WHAT GOES HERE?->otherstuff
However I cant hard code the [2010-12] because its a date, is there any way I can call e.g. $response->stuff->nextsibling->stuff
I hope this makes sense to someone :D Currently i'm bastardising this with a $key => $value for loop and extracting the key value and using it in my $response->stuff->$key->stuff call.
stdClass Object
(
[commentary] =>
[stuff] => stdClass Object
(
**[2010-12]** => stdClass Object
(
[otherstuff] => stdClass Object
(
[otherstuffrate] => 1
[otherstufflevel] => 1
[otherstufftotal] => 1
)
)
)
)
StdClass instances can be used with some Array Functions, among them
current — Return the current element in an array and
key — Fetch a key from an array
So you can do (codepad)
$obj = new StdClass;
$obj->{"2012-10"} = 'foo';
echo current($obj); // foo
echo key($obj); // 2012-10
On a sidenote, object properties should not start with a number and they may not contain dashes, so instead of working with StdClass objects, pass in TRUE as the second argument to json_decode. Returned objects will be converted into associative arrays then.
The date key must be a string, otherwise PHP breaks ;).
echo $response->stuff['2010-12']->otherstuff
Retrieve it using a string.
Edited again: added object code also
json decode it as associative array, and use key fetched through array_keys . See it work here : http://codepad.org/X8HCubIO
<?php
$str = '{
"commentary" : null,
"stuff" : {
"ANYDATE" : {
"otherstuff": {
"otherstuffrate" : 1,
"otherstufflevel" : 1,
"otherstufftotal" : 1
}
}
}
}';
$obj = json_decode($str,true);
$reqKey = array_keys($obj["stuff"]);
$req = $obj["stuff"][$reqKey[0]]["otherstuff"];
print_r($req);
print "====================as object ============\n";
$obj = json_decode($str);
$req = current($obj->stuff)->otherstuff;
print_r($req);
?>

Categories