json decode array PHP - php

I'm trying to decode a json string, i want to get just langlinks value,
my json string is:
{
"batchcomplete": "",
"query": {
"pages": {
"105219": {
"pageid": 105219,
"ns": 0,
"title": "Cancer",
"langlinks": [
{
"lang": "ar",
"*": "\u0633\u0631\u0637\u0627\u0646"
}
]
}
}
}
}
I tried this code:
$results = json_decode($api_response, true);
$list = array();
foreach ($results['query']['pages'] as $k => $v)
{
var_dump($v);
foreach($v as $key => $val)
{
array_push($list, $val);
}
}
return $list;
But it does not accede to the value that I want, when i add
var_dump(array_key_exists('langlinks', $v));
it gives me false :/

I just tested this and this seems to return true
$source = file_get_contents('https://en.wikipedia.org/w/api.php?action=query&titles=Cancer&prop=langlinks&lllang=ar&format=json');
$results = json_decode($source, true);
foreach ($results['query']['pages'] as $k => $v)
{
var_dump(array_key_exists('langlinks', $v));die();
}
If you are still having trouble, maybe you can post more code?

$list = array();
$src = json_decode($api_response, true);
foreach ($src['query']['pages'] as $key => $langData) {
foreach ($langData['langlinks'] as $k => $ld);
// var_dump($ld['*']);
}
return $ld['*'];

Related

Removing JSON children by key in PHP

My goal is to have a function that can remove a specified json child, which could also be nested inside deeper.
My function looks like this:
private function removeJsonChild(String $jsonKey, String $jsonString)
{
$json = json_decode($jsonString, true);
$arr_index = array();
foreach ($json as $key => $value) {
if (is_array($value)) {
$json[$key] = $this->removeJsonChild($jsonKey, json_encode($value));
}
if ($key == $jsonKey) {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json[$i]);
}
return json_encode($json);
}
The function would work if i wouldn't check if a $value is an array and then call the function again recursively. But there is the problem i think. In the statement where i assign the return value of the function to $json[$key]. What am i doing wrong?
EDIT: definitely forgot a json_decode. New code looks like this:
private function removeJsonChild(String $jsonKey, String $jsonString)
{
$json = json_decode($jsonString, true);
$arr_index = array();
foreach ($json as $key => $value) {
if (is_array($value)) {
$json[$key] = json_decode($this->removeJsonChild($jsonKey, json_encode($value)));
}
if ($key == $jsonKey) {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json[$i]);
}
return json_encode($json);
}
EDIT2:
The function works now, however it slightly changes the json schema.
An JSON like this:
[
{
"id": 1,
"name": "oyzadsaigny647"
}
]
now becomes this:
{
"1": {
"id": 1,
"name": "oyzadsaigny647"
}
}
private function removeJsonChild(String $jsonKey, String $jsonString) {
$data = json_decode($jsonString, true);
$data = $this->removeKeyFromArray($key, $data);
return json_encode($data);
}
private function removeKeyFromArray(String $deleteKey, array $data) {
unset($data[$deleteKey]); // No need to check if it exists, it just does nothing in that case
foreach($data as $key => value) {
if(is_array($value)) {
$data[$key] = $this->removeKeyFromArray($deleteKey, $value);
}
}
return $data;
}
NOTE: this will work in case of dictionaries, i.e. array with actual keys. If you have a plain array such as [1, 10, 23, 15] the unset behaviour is wrong, as pointed out by #decezeā™¦

Json data group by team name with php

I have to display team points under respective team name
I have following json data
{
"id":319231,
"innings":[
{"id":967766},
{"id":967767},
{"id":967768},
{"id":967769}
],
"team1":{
"team":{"name":"Minor Counties","id":115104,"club":{"name":"Minor Counties","id":98110}},
"innings":[
{"id":967766,"points":253,"wickets":10,"overs":86,"balls":4},
{"id":967768,"points":190,"wickets":5,"overs":61,"balls":0}
]
},
"team2":{
"team":{"name":"Major Counties","id":93648,"club":{"name":"Major Counties","id":35487}},
"innings":[
{"id":967767,"points":229,"wickets":10,"overs":67,"balls":4},
{"id":967769,"points":64,"wickets":4,"overs":23,"balls":2}
]
},
}
Now I want result like :
Minor Counties Major Counties
253/10 & 190/5 229/10 & 64/4
Currently I am getting result like :
Minor Counties Minor Counties Major Counties Major Counties
253/10 190/5 229/10 64/4
Here is my php code so far :
$team1 = $read_json->team->team1->name;
$team2 = $read_json->team->team2->name;
foreach($read_json->team1->innings as $team1Innings){
$points = $team1Innings->points;
$wickets = $team1Innings->wickets;
$overs = $team1Innings->overs;
$balls = $team1Innings->balls;
echo "<div class=\"score-total\"><span class=\"score-team\">$team1</span>$points/$wickets<span class=\"score-overs\">$overs.$balls overs</span></div>";
}
similar code to get team2 points
$json = '{
"id":319231,
"innings":[
{
"id":967766
},
{
"id":967767
},
{
"id":967768
},
{
"id":967769
}
],
"team1":{
"team":{
"name":"Minor Counties",
"id":115104,
"club":{
"name":"Minor Counties",
"id":98110
}
},
"innings":[
{
"id":967766,
"points":253,
"wickets":10,
"overs":86,
"balls":4
},
{
"id":967768,
"points":190,
"wickets":5,
"overs":61,
"balls":0
}
]
},
"team2":{
"team":{
"name":"Major Counties",
"id":93648,
"club":{
"name":"Major Counties",
"id":35487
}
},
"innings":[
{
"id":967767,
"points":229,
"wickets":10,
"overs":67,
"balls":4
},
{
"id":967769,
"points":64,
"wickets":4,
"overs":23,
"balls":2
}
]
}
}';
$items = json_decode($json);
unset($items->id);
unset($items->innings);
foreach ($items as $item) {
echo "<b>{$item->team->name}</b>";
$innings = [];
foreach ($item->innings as $inning) {
$innings[] = "{$inning->points} / {$inning->wickets}";
}
echo '<br>';
echo implode(' & ', $innings);
echo '<br>';
}
Use json_decode() with true as second parameter it gives you an associative array and it will convert the JSON object into a PHP object.It will make your life easier.
Try this :
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $teamData) {
if(!empty($teamData[team][name])) {
echo $teamData[team][name].'<br>';
$inningsPoint = [];
}
foreach ($teamData[innings] as $inningsData) {
$inningsPoint[] = "$inningsData[points] / $inningsData[wickets]";
}
echo implode(' & ', $inningsPoint);
}
Demo!
<?php
function showteams_results($k1,$points){
switch ($k1) {
case 'team1':
foreach ($points as $key => $value) {
if($key=="team1")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
case 'team2':
foreach ($points as $key => $value) {
if($key=="team2")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
default:
echo "Team no points!";
break;
}
}
$points=array();
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $k1 => $teamData) {
//extracting points of team1---------->
if($k1=="team1"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team1"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
//extracting points of team2---------->
if($k1=="team2"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team2"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
}
?>

Foreach getting value null, why?

I am trying to get access to some data in PHP. If I print my docuements as a JSON object I get the document like so:
print_r($url);
[
{
"channel": "hello.com",
"partone": {
"click": 30580,
"load": 2156552
},
"parttwo": {
"click": 3274,
"load": 402327
},
"partthree": {
"click": 406467,
"load": 903869
}
}
]
So my main idea is to get the "click" of "parttwo" but I am getting null. This is my PHP code where I am making the mistake:
foreach ($url[0]['parttwo'] as $obj) {
$doc = array();
$doc['click'] = $obj['click'];
$param []= $doc;
}
Fo that data, simply:
$array = json_decode($url, true);
$param = $array[0]['part2']['click'];
If you really need to loop then:
foreach($array as $value) {
$param[] = $value['part2']['click'];
}

foreach inside static array

How can I replace the locations here with a foreach loop? When I put the foreach inside of the array, the code breaks. I guessing the answer has to do with creating a foreach variable and then entering that for the levels value instead?
This is my array
$data = array(
'name' => Locations,
'data' => '{
"title":"USA",
"location":"World",
"levels":[
{
"id":"states",
"title":"States",
"locations":[
{
"id":"ca",
"title":"California",
"pin":"hidden",
"x":"0.0718",
"y":"0.4546",
},
{
"id":"wa",
"title":"Washington",
"pin":"hidden",
"x":"0.1331",
"y":"0.0971"
}
]
}
]
}'
Here is my current foreach.
foreach ($response->records as $record) {
$id = $record->Id;
$title = $record->Title;
$pin = $record->Pin;
$x = $record->X;
$y = $record->Y;
echo {
"id": $id,
"title": $title,
"pin": $pin,
"x": $x,
"y": $y
}
}
Any help would be appreciated.
$arr = array();
foreach ($response->records as $record) {
$r['id'] = $record->Id;
$r['title'] = $record->Title;
$r['pin'] = $record->Pin;
$r['x'] = $record->X;
$r['y'] = $record->Y;
$arr[] = $r;
}
echo json_encode($arr);

Multidimensional array to linear array?

I have here a multidimensional array.
{
"date_start": [
"2013-09-30",
"2013-09-27",
],
"time_start": [
"2013-09-30 08:41:00",
"2013-09-27 09:01:00",
],
"time_out": [
"2013-09-30 18:37:00",
"2013-09-27 21:11:00",
],
}
Is it possible to convert this to a linear array? to something like this?
{
[{"date_start":"2013-09-30","time_start":"2013-09-30 08:41:00","time_out":"2013-09-30 18:37:00"},
{"date_start":"2013-09-27","time_start":"2013-09-30 09:01:00","time_out":"2013-09-30 21:11:00"}]
}
I'm having a hard time to think how to do it T_T. thanks for anyone who could help me.
UPDATE:
This is now my updated work. Thanks to Nil'z for enlightening me to use decode. Just need a little more tweek.
$data_en = json_encode($data);
$data_de = json_decode($data_en, true);
$test = array();
foreach($data_de as $key => $value)
{
echo $key."<br/>";
foreach($value as $k => $v)
{
echo "$k |";
echo json_encode($v)."<br/>";
}
}
Here is now the output but still need to work something out:
date_start
0 |"2013-09-30"
1 |"2013-09-27"
time_start
0 |"2013-09-30 08:41:00"
1 |"2013-09-27 09:01:00"
time_out
0 |"2013-09-30 18:37:00"
1 |"2013-09-27 21:11:00"
If its JSON try like this:
<?php
$data = array();
$array = json_decode( $mainArray ); #decode the JSON
foreach( $array as $key => $each ){
$data[$key]['date_start'] = $each['date_start'];
$data[$key]['time_start'] = $each['time_start'];
$data[$key]['time_out'] = $each['time_out'];
}
#again encode the JSON
$data = json_encode( $data );
print_r( $data );
?>
You could try with recursive function:
function array_multi_to_linear($arr) {
static $rez;
foreach($arr as $v) {
if (is_array($v)) {
array_multi_to_linear($v);
} else {
$rez[] =$v;
}
}
return $rez;
}

Categories