Retrieve first element of JSON with php [duplicate] - php

This question already has answers here:
Parsing JSON in PHP
(2 answers)
Closed 5 years ago.
I got a JSON from a web site in the raw format:
{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}, ... }
How do I get the A_B and A_C??? I do not know what A_B and A_C could be.

Try the following.
$json = file_get_contents("your json data");
$arr = json_decode($json, true);
foreach ($arr as $key=>$val) {
var_dump($key);
}
Finally, var_dump($key) displays A_B and A_C.

Suppose you have that raw json in some variable, say $yourJson
First, parse your json. $parsedJson = json_decode($yourJson, true)
Then run a foreach loop and stop after 2 iterations, You will (hopefully) get the right key-value pair.
$i = 0;
$extractedValues = [];
foreach ($parsedJson as $key => $value) {
$extractedValues[$key] = $value; $i++;
if ($i === 2) {
break;
}
}
Now, $extractedValues contains only two elements found from the first two iterations.

$data = json_decode("Your json variable");
foreach($data as $value){
echo $value; // here you receive your desire value.
}

Try this:
$json = '{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}}';
$dataArray = json_decode($json, true);
$arrayKeys = array_keys($dataArray); // in your case A_B and A_C
and if you want to get their values then:
foreach($dataArray as $data) {
foreach($data as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
}

var $jsonObj = json_decode('{"A_B":{"id":7,"last":"0.00000038"}}')
print $jsonObj->{'A_B'}

Related

Working with json data returned by web service [duplicate]

This question already has answers here:
How to convert a string to JSON object in PHP
(6 answers)
Closed 4 years ago.
I have created a Soap client to request data from web services and the returned data is displayed like this with my CodeIgniter function"
{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}
but I want to format them like this by removing the getCodeResult
{"selling":"1000.67114","Buying":"9000.65789"}
I hope this may help you.
<?php
$jsonData = '{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}';
$data = json_decode($jsonData, true);
$arr_index = array();
foreach ($data as $key => $value) {
$arr_index = $value;
}
echo json_encode($arr_index, true);
?>
Thanks.
If you want to get only the values of selling and buying means, try like below.
<?php
$jsonData = '{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}';
$data = json_decode($jsonData, true);
$arr_index = array();
foreach ($data as $key => $value) {
if($key == 'GetCodeResult'){
$arr_index = $value;
}
}
foreach($arr_index as $values){
$finalVal[] = $values;
}
echo json_encode($finalVal, true);
?>
Decode to array and return only the 'GetCodeResult' then json_encode it.
echo json_encode(json_decode($json, true)['GetCodeResult']);
//{"Selling":"1000.67114","Buying":"9000.65789"}
https://3v4l.org/59RSc
To only echo the values you can assign them to variables using list and array_values.
list($selling, $buying) = array_values(json_decode($json, true)['GetCodeResult']);
echo $selling .PHP_EOL;
echo $buying .PHP_EOL;
//1000.67114
//9000.65789
https://3v4l.org/T5GNg

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 do I implode a json object to a string in php? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this json held in a variable that I am trying to convert to a string?
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
What I want as my end result is something that looks like this:
$json_object1 = '1,2,3,4,5,6,7,8,9,10,11';
$json_object2 = '125,126,127,128,129,130,131,132,133,134,135';
Is there a way we can modify the implode(",",$json_object) function to achieve this?
Another question:
Any idea how we might put this
{"26":"Child - 1500.00","28":"Foreigner - 4000.00","27":"Resident - 3000.00"}
To a list like
26 : Child - 1500.00
27: Resident - 3000.00
28: Foreigner - 4000.00
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$json = json_decode($json_object);
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $p;} }, $json));
echo "<br>";
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $v;} }, $json));
See https://3v4l.org/p3p45
Try this:
<?php
$jsonString = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$decoded = json_decode($jsonString, true);
$keys = [];
$values = [];
foreach($decoded as $item) {
foreach($item as $key => $value) {
$keys[] = $key;
$values[] = $value;
}
}
$resultStringKeys = implode(",", $keys);
$resultStringValues = implode(",", $values);
var_dump($resultStringKeys, $resultStringValues);
The output:
string(43) "125,126,127,128,129,130,131,132,133,134,135"
string(23) "1,2,3,4,5,6,7,8,9,10,11"
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$arr1 = []; $arr2=[];
$jsonobj = json_decode($json_object);
foreach ($jsonobj as $val){
$Arrval = (array) $val;
foreach ($Arrval as $k=>$v){
$arr1[]=$k;
$arr2[]=$v;
}
}
$json_object1 = implode(",",$arr1);
$json_object2 = implode(",",$arr2);
Out put is
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11
Another possible solution (not the best if the size of your JSON input is measured in MBs but good enough for several KBs of input):
$input = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
// Decode the JSON into arrays; TRUE as the second argument requires arrays, not objects
$data = json_decode($input, TRUE);
// Run through the list, extract the data into a new list
$output = array_reduce(
$data,
function(array $carry, array $item) {
// Put the keys and values of $item into the corresponding lists on $carry
$carry['keys'] = array_merge($carry['keys'], array_keys($item));
$carry['vals'] = array_merge($carry['vals'], array_values($item));
return $carry;
},
// Start with empty lists of keys and values
array('keys' => array(), 'vals' => array())
);
// That's all; $output['keys'] contains the keys, $output['values'] contains the values.
echo('Keys: '. implode(',', $output['keys'])."\n");
echo('Values: '.implode(',', $output['vals'])."\n");
You can achieve like this,
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$key_arr = array();
$val_arr = array();
$json_arr = json_decode($json_object);
foreach($json_arr as $val)
{
foreach($val as $key => $value)
{
$key_arr[] = $key;
$val_arr[] = $value;
}
}
$resultStringKeys = implode(",", $key_arr);
$resultStringValues = implode(",", $val_arr);
And echo your $resultStringKeys and $resultStringValues and you will get your output.
first convert json data to php array then store all key and value in different array then implode it
<?php
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$array_data = json_decode($json_object, true);
foreach($array_data as $data) {
foreach($data as $key => $value) {
$array_key[] = $key;
$array_value[] = $value;
}
}
$final_key = implode(",", $array_key);
$final_value = implode(",", $array_value);
echo $final_key;
echo "<br>";
echo $final_value;
then output is :
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11

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

Retrieving array keys from JSON input

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

Categories