Reading item in PHP Multi Array - php

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'];
}

Related

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

How to iterate JSON using PHP?

Can any one tell me how to iterate below given JSON data using PHP,
{
"value1":"3",
"value 2":"5",
"Id":[
"210",
"211"
]
}
<?php $json='{ "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
$getarr=json_decode($json,true);
foreach( $getarr as $key => $value)
{
if(is_array($value))
{
// ID has an array so retrieve a value
foreach($value as $key1 => $value1)
{
echo $key."=>".$value1;
}
}else
{
echo $key."=>".$value;
}
} ?>
It will be produce the below output. Hope it will be helpful to solve your problem
Answer:
value1=>3 value 2=>5 Id=>210 Id=>211
Use json_decode function for converting it to array.
$array = json_decode( $json, true );
Copy and paste you can change the print out to fit your use
<?php
$bar=' { "value1":"3", "value 2":"5", "Id":[ "210", "211" ] }';
//var_dump($bar);
$JSONdata = json_decode($bar, true);
//echo
$JSONdataValue="";
$JSONdataValue.=$JSONdata['value1']."<br>";
$JSONdataValue.=$JSONdata['value 2']."<br>";
$JSONdataValue.=$JSONdata['Id'][0]."<br>";
$JSONdataValue.=$JSONdata['Id'][1]."<br>";
echo $JSONdataValue;
?>

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

PHP - Getting array element from Json

I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/
I'm trying to get the tags[{"name":""}] part of it. For example, I would want the 'container', from '"name":"Container"'
This is my code here:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}
tags[] is an array, though I did tags[1], I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.
The simplest way may be to do an extra loop to grab all the name elements:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
foreach($mydata->tags as $tag) {
echo $tag->name;
}
}
or to get the first name of each tag group:
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[0]->name;
}
I updated the whole answer:
$json = json_decode($data, true);
if (isset($json['rgDescriptions']) && is_array($json['rgDescriptions'])){
foreach ($json['rgDescriptions'] as $array_no => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'])){
echo "{$array_no}::::";
foreach ($json['rgDescriptions'][$array_no]['tags'] as $k => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'][$k]['name'])){
echo "{$json['rgDescriptions'][$array_no]['tags'][$k]['name']},";
}
}
echo "<br />";
}
}
}

JSON parsing with PHP - most efficient way

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

Categories