JSON parsing with PHP - most efficient way - php

I send JSON object to server. On server side I have to parse this obj with PHP.
I'm stuck in the loop. I don't know how to proceed inside loops.
Im looking for most efficient way to parse this object and save all variables into DB.
[
{"ADI":{"id":-1,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ALE":{"_id":1,"_name":"Milk","contain":false}},
{"ALE":{"_id":2,"_name":"cfg","contain":false}},
{"ALE":{"_id":4,"_name":"Lakt","contain":false}},
{"PRO":{"image":"","code":"123456","name":"jfbj"}},
{"USER":{"email":"spam#spam.com"}}
]
For now I have done this:
$string = file_get_contents('php://input');
$array = json_decode($string, true);
//print_r($array);
foreach ($array as $t => $index) {
foreach ($index as $vas => $r) {
//Here I'm stuck!!!
}
}

you can grab values from json
<?php
$string = '[
{"ADI":{"id":-1,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ADI":{"id":3,"danger":0}},
{"ALE":{"_id":1,"_name":"Milk","contain":false}},
{"ALE":{"_id":2,"_name":"cfg","contain":false}},
{"ALE":{"_id":4,"_name":"Lakt","contain":false}},
{"PRO":{"image":"","code":"123456","name":"jfbj"}},
{"USER":{"email":"spam#spam.com"}}
]';
$array = json_decode($string, true);
echo "<pre>";
//print_r($array);exit;
for ($i=0;$i<=(count($array)-1);$i++){
//print_r($array[$i]);
if (array_key_exists("ADI",$array[$i])) {
$ArrVal = $array[$i]['ADI'];
$id = $ArrVal['id'];
$danger = $ArrVal['danger'];
echo "$id,$danger ";
}
}
?>

check this out :
echo "<pre>";
print_r($array);
for ($i=0; $i < count($array); $i++) {
if(isset($array[$i]["ADI"])){
print_r($array[$i]["ADI"]);
}
if(isset($array[$i]["ALE"])){
print_r($array[$i]["ALE"]);
}
}
echo "</pre>";

Related

i cant get json array value using loop for (PHP)

i have 1 json but i cant get a value using for loop
$string = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($string,true);
for($i = 0;$i<count($json);$i++){
for($j = 0;$j<count($json->lot);$i++){
if($json->lot==0){
echo $j;
}
}
}
i got this error : Trying to get property of non-object
edit your code :
$json = [{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]
$json = json_decode($json);
for($i = 0;$i<count($json);$i++){
for($j = 0;$j<count($json->lot);$i++){
if($json->lot==0){
echo $j;
}
}
changes json to decode in array using php json_decode(). json_decode
You need to use json_decode on your json. Also, keep in mind that json have to be stored as string in PHP.
<?php
$json = ['{"lt":"1","lot":["1","1","1","1","1"]}','{"lt":"2","lot":["0","0","0","0","0"]}','{"lt":"3","lot":["0","0","0","0","0","0"]}'];
foreach($json as $data) {
$current = json_decode($data);
foreach($current->lot as $lot)
echo $lot;
}
Used json_decode() function for decode json :
<?php
$json = '[{"lt":"1","lot":["1","1","1","1","1"]},{"lt":"2","lot":["0","0","0","0","0"]},{"lt":"3","lot":["0","0","0","0","0","0"]}]';
$json = json_decode($json);
foreach($json as $val){
foreach($val->lot as $lot) {
if($lot==0){
echo $lot;
}
}
}
?>

get index of json key using php

I want to find index of key from json array similar to this question Get index of a key in json
but i need the solution using php.
here is my json (partial data)
{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}
and php
foreach ($read_json->scorecards->batting->players as $batsmen => $val) {
if($val == 5) { // if batsman index is 5 then display his name
$name = $batsmen->name;
echo "<div>$name</div>\n";
}
}
Please help me to solve this issue.Thanks in advance.
I think this would suffice your requirement
http://codepad.org/XQDCKAsB
Find the code sample below as well.
$json = '{"currentOver":{"events": []},"matchString":"","currentPlayer":5,"previousOvers":[],"innings":[],"scorecards":[{"batting":{"players":[{"id":16447,"name":"Rahul Roy"},{"id":12633,"name":"Sijal Thomas"},{"id":16446,"name":"Mohammed Reza"},{"id":16509,"name":"Asif Khan"},{"id":12633,"name":"Koyel Dijesh"},{"id":16468,"name":"Shahrook"},{"id":64691,"name":"Shafiq"},{"id":6518,"name":"Ubaidulah"}]}}]}';
$arr = json_decode($json);
echo '<pre>';
$currentPlayer = $arr->currentPlayer;
echo $arr->scorecards[0]->batting->players[$currentPlayer-1]->name;
Try this code.
$info = json_decode('json string');
$currentPlayer = $info->currentPlayer;
$batsman = $info->scorecards[0]->batting->players[$currentPlayer];
echo "<div>{$batsman->name}</div>\n";
Also, note that arrays in PHP are zero-based. If currentPlayer index in json data is based on 1 (rare case, but it exists sometimes) you will ned to use
$batsman = $info->scorecards[0]->batting->players[$currentPlayer - 1];
to get right item from array.
If you just want to fix your foreach
$read_json->scorecards->batting should become $read_json->scorecards[0]->batting
if($val == 5) should become if($batsmen == 5)
$name = $batsmen->name; should become $name = $val->name;
You need to use json_decode and array_keys for the array keys from the json.
$json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
$result = json_decode ($json, true);
$keys = array_keys($result);
print_r($keys); //Array ( [0] => key1 [1] => key2 [2] => key3 )
In Php, You can use the code below, if you wan to fix it using foreach loop
foreach($json->entries as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
please have a look following code
$json=json_decode($data)->scorecards[0]->batting->players;
foreach ($json as $key => $value) {
if($key==5){
echo $value->name ;
}
}
You can do it using converting JSON string to Array
$json_str = '{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}';
Decode your JSON string using "json_decode" and you get array
$json_decode_str = json_decode($json_str, true);
Now using foreach you can do anything
if($json_decode_str['scorecards']){
foreach($json_decode_str['scorecards'] as $scorecard){
$player_index = 1;
if($scorecard['batting']['players']){
foreach($scorecard['batting']['players'] as $player){
if($player_index == 5){
echo $player['name'];
}
$player_index++;
}
}
}
}
Maybe this one help you :)

Reading item in PHP Multi Array

I would like to read the following JSON info in PHP using a foreach. Im new to this and need some help. I have only included a small sample of the data for privacy reasons.
The end goal is to get all the "id" and the "real_address" in the server array.
[
{
"id":"d87df8g7sdfg89",
"status":false,
"servers":[
{
"status":false,
"platform":null,
"server_id":"adsfasdfasdfasdf",
"virt_address6":"fd00:c0a8:f800:0:192:168:248:5",
"virt_address":"192.168.248.5",
"name":"Private",
"real_address":null,
"connected_since":null,
"id":"aasdfasdfasdfsafde",
"device_name":null
}
],
},
{
"id":"asd89asd8f",
"status":true,
"servers":[
{
"status":true,
"platform":"linux",
"server_id":"fasdsdfasdfasdf",
"virt_address6":"fd00:c0a8:f800:0:192:168:248:3",
"virt_address":"192.168.248.3",
"name":"Private",
"real_address":"5.5.5.52",
"connected_since":1447406908,
"id":"asdfasdfasdfasdf",
"device_name":"thriving-fields-2667"
}
],
}
]
You can use json_decode
$data = json_decode($json, true);
foreach ($data as $value) {
foreach ($value['servers'] as $server) {
echo $server['real_address'];
}
}
something like this ...
$items = json_decode($json);
foreach($items as $item){
foreach($item->servers as $server)
{
echo $server->server_id . " - ". $server->status;
}
}
If you have PHP >= 5.5.0 for array_column() you can try this:
$array = json_decode($json, true);
foreach (array_column($array, 'servers') as $server) {
echo $server['real_address'];
}

Count how many of the same element in json

Im parsing json with php in this simple piece of code
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
foreach($records as $record)
{
echo $record['number']." ".$record['opened_at'];
}
?>
But i want to echo how many 'number' element are in my json file exemple bellow
{
"records":[
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
$numberCount = 0;
foreach($records as $record)
{
$numberCount += isset($record['number']); // Here we go
echo $record['number']." ".$record['opened_at'];
}
echo $numberCount;
?>
This function might be helpful: http://www.php.net/manual/en/function.array-count-values.php
$counts = array_count_values($records);
$numberCount = $counts['number'];

Converting Strings to JSON Convertable Arrays

I am querying a database for results and trying to convert them into JSON encodable array where the key will act as the name of the pair and the value is the value. How would I do this in the following code below?
foreach($results as $result) {
foreach( $result as $key => $value ) {
if ($key == 'D')
{
$trimmed = round($value, 4);
}
else
{
$trimmed = trim($value, "\n\r");
}
$array[$i] ="$key"."=>"."$trimmed";
}
$i = 0;
$jret = json_encode($array);
echo $jret;
}
For example:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
dunno what you need and why you mimic PHP code instead of using it, but may be
$array[] = array($key => $trimmed);
is what you are looking for
with
$array[$i][$key] = $trimmed;
you could do
$return = json_encode($object, JSON_FORCE_OBJECT);
at the end

Categories