json decode with an array in php - php

I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.

If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];

How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];

You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}

Related

php filtering json file and returning an attribute value

I have a json file which I read in. I want to first filter the json data to return the object defined by the datasetID, then get out the datasetName. I have filtered in javascript, but would prefer to stay in php but I can't figure it out, any ideas?
note: foreach is not required as only a single record is returned when filtered using the datasetID. So rather than using a foreach method how would you swelect a single record, first for instance?
$datasetID = '5fd4058e5c8d2'; // unique 13 character string
$data = json_decode(file_get_contents(path/to/file), True);
So I need to first filter for the unique object with $datasetID = '5fd4058e5c8d2';
$filtered_data =
Then I need to return the attribute datasetName from that object
$datasetName =
pointers to the best ways to do this is welcomed.
Sample json data:
[
[
{
"datasetID":"5fd4124900827",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None"
}
],
[
{
"datasetID":"5fd4058e5c8d2",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None",
}
]
]
I don't know how you got that JSON but it is nested deeper than needed. You can merge the top level arrays to flatten it, then index on datasetID:
$data = array_merge(...$data);
$filtered_data = array_column($data, null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Shorter:
$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Or to keep them all to use:
$data = array_column(array_merge(...$data), null, 'datasetID');
$datasetName = $data[$datasetID]['datasetName'];
I tried with your sample JSON.
First, json_decode will return a PHP array to use foreach on it. I wrote a simple foreach and checked your searching ID is equal to element's datasetID. If it is equal this is the datasetName you are searching for.
<?php
$json = '[[{"datasetID":"5fd4124900827","institutionCode":"None","collectionCode":"None","datasetName":"None"}],[{"datasetID":"5fd4058e5c8d2","institutionCode":"None","collectionCode":"None","datasetName":"None"}]]';
$elements = json_decode($json,TRUE);
$searchingID = "5fd4058e5c8d2";
foreach ($elements as $element) {
if(isset($element[0]['datasetID']) && $element[0]['datasetID'] == $searchingID){
$filtered_data = $element[0];
break;
}
}
echo $filtered_data['datasetName']; // or return $filtered_data['datasetName'];
?>

Getting values from key value pairs PHP

I have a registration form which saves user data to a text file via the serializable method.
a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}
I can deserialize the data however I am having some trouble extracting the value "Mario" from the key - "name". Code can be seen below:
$array = file_get_contents('user.txt');
$artikel = unserialize($array);
foreach ($artikel as $item ){
echo $item['name'];
}
The error I recieve is Illegal string offset 'name'. Any help would be greatly appreciated.
You have a serialized array of JSON strings.
So try like this
//$array = file_get_contents('user.txt');
$artikel = unserialize('a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}');
//print_r($artikel);
foreach ($artikel as $item ){
$json = json_decode($item);
echo $json->name;
}
PS: Storing a password in plain text is very bad security, storing that in a simple file is even worse security, so I hope system this will never actually be used. PHP provides password_hash()
and password_verify() please use them.
You need to json_decode after foreach with true as a second parameter then you will get array as you want..
<?php
$arr = 'a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}';
$artikel = unserialize($arr);
foreach ($artikel as $item ){
$response = json_decode($item, true);
echo $response['name'];
}
?>

convert an array of arrays to json

i want to convert this array as shown below
array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
into this format:
"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}
I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.
thanks in advance
Before converting into json, you should change the array:
$array_countries_formated = array();
foreach ($array_countries as $item)
{
$array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
}
echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);
Result:
{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}
Try this...
<?php
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
$jsonString = json_encode($array_countries);
print_r($jsonString);
?>
Result:
{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}}
If I understand your requested output correctly, the following should do the trick:
$result = array();
foreach ($array_countries as $country) {
$cntryValue = $country["cntryValue"];
if (!array_key_exists($cntryValue, $result)) {
$result[$cntryValue] = array();
}
$result[$cntryValue][$country["cntryLabel"]] = array();
$result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"];
}
echo json_encode($result) . "\n";
A little explanation: the array provided ($array_countries) is formatted differently as compared to your requested output. Therefore, it should be converted. That is what the foreach loop does. The formatted result can be converted to json using the json_encode function.

Accessing first element of stdobject

I am using an API where I get the following response:
{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}, ... }
It is no problem to access the object when I would know the key like
$result = json_decode(file_get_contents($url));
$result->BTC_LTC->last
In my case I do not know the XXX_XXX keys. How can I get the keys? I tried things like $result->{0} / $result->[0] / $result{0} / $result[0] without success.
How can I retrieve the values of XXX_XXX (e.g. in the example above BTC_LTC)?
This should do the trick:
<?php
$json = '{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}}';
$result = json_decode($json);
$vars = get_object_vars($result);
$keys = array_keys($vars);
echo $vars[$keys[0]]->last;
?>
You can try the code here
Use a foreach loop that should work
foreach($result as $k=>$v)
{
.
.
.
}
The second argument to json_decode allows specifying that you want an array returned:
$result = json_decode(file_get_contents($url),true);
Now that result is an array you can use it as usual (looping, array_keys, e.t.c.).

How to parse second level of json php

I have a json like this:
[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]
I want to get in php each row for update my database. I don't know the number of second level json are. Sometimes will be 1, sometimes 2 and sometimes more.
I thought, I could read it doing something like this:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
//Bla bla
$i++;
}
I have used many times json file in php but always, just one level. This is my first time with more than one.
But I can't. I know, because I checked, that in $json I have the complete json file.
You need to reference the subkey in your array:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
echo $json_post[$i]["a"];
// or
echo $json_post[$i][0];
$i++;
}
More docs can be found here: http://php.net/manual/en/language.types.array.php
And a similar question here: PHP reference specific key and value within multidimensional array
i'd use foreach:
foreach($json_post as $key => $value) {
echo $value;
}
$j = '[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]';
$decoded = json_decode($j, true);
//var_dump($decoded);
foreach ($decoded as $key => $post) {
$valueOfA = $post['a'];
$valueOfB = $post['b'];
}

Categories