Retrieving array keys from JSON input - php

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?

Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values

You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.

I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php

You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);

foreach($json->entries[0] AS $key => $name) {
echo $key;
}

$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}

Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

Related

creating one loop for parsing json data

So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.

How to get json property name with php

So here's the thing, I get this json from a url ( in my context i get it from a url, but let's say here I write my json in a variable :
$file = '[
{"status": "5.4.1","email": "dddddd#exelcia-it.com"},
{"status": "5.4.1",, "email": "sksksksk#exelcia-it.com"}
]'
Then I do $json = json_decode($file,true);
And I want to get all the emails so I do :
foreach ($json as $key => $value) {
echo $value["email"]. "<br>";
}
But what I also need, is to return something like that from the loop (only for one property):
"email = dddddd#exelcia-it.com".
So I need to also get the name of the property but I can't figure this out.
I tried
foreach($json as $key => $propName){
echo $key.'<br>';
}
But I just get the index (0,1,...), not what I want.
Thanks!
You have to loop each json row, this should works:
$file = '[{"status": "5.4.1","email": "dddddd#exelcia-it.com"},{"status": "5.4.1", "email": "sksksksk#exelcia-it.com"}]';
$json = json_decode($file,true);
foreach($json as $row)
{
foreach($row as $key => $value)
{
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
Use this loop to get key and value pairs together.
foreach($data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
Ok thanks that's what I needed !
For me I just need the email properties and values, so I do :
foreach($json as $row)
{
foreach($row as $key => $value)
{
if($key=='email'){
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
}
Awesome ! thanks !

Getting formatted result with nested arrays in PHP

I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>

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

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Categories