I am getting following response in JSON format and I want it to convert it into PHP variables.
JSON:
{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900"
,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}
output should be PHP:
$transkey = aa900d54-7bfb-47e9-a5de-e423ec34a900;
$vkey = fbb28b32-f439-4801-a434-99c70aa388ca
please advice me how to do it.
Just simply use json_decode();
$result= json_decode($jSon);
var_dump($result); // to see the output
json to array(json_decode) and then extract from array.
$arr = json_decode($json, true);
extract($arr);
var_dump($CreateTransactionResponse);
Output:
array (size=1)
'CreateTransactionResult' =>
array (size=3)
'TransportKey' => string 'aa900d54-7bfb-47e9-a5de-e423ec34a900' (length=36)
'ValidationKey' => string 'fbb28b32-f439-4801-a434-99c70aa388ca' (length=36)
'Messages' =>
array (size=0)
empty
More about extract
use $CreateTransactionResult['TransportKey'] to access Transport Key from JSON. Similarly $CreateTransactionResult['ValidationKey'] for Validation Key.
If you want to access your json try to decode it first:
$result = json_decode($yourJSON, true);
foreach($result['CreateTransactionResponse'] as $key => $val){
echo $transkey = 'TransportKey= ' . $val['TransportKey'] . '<br/>;
echo $vkey = 'ValidationKey= ' . $val['ValidationKey'];
}
Or if it is an array of JSON's
$result = json_decode($yourJSON, true);
$data = [];
foreach($result['CreateTransactionResponse'] as $key => $val){
$data[] = [
'TransportKey' => $val['TransportKey'],
'ValidationKey' => $val['ValidationKey']
];
}
print_r($data);
try this code it will work
$JSON='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900" ,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
$arr=json_decode($JSON, TRUE);
foreach ($arr as $value) {
foreach ($arr['CreateTransactionResponse'] as $key => $var) {
echo 'TransportKey = '.$var['TransportKey'].'<br>';
echo 'ValidationKey = '.$var['ValidationKey'].'<br>';
foreach ($var['Messages'] as $key => $msg) {
echo 'Messages = '.$msg.'<br>';
}
}
}
In this case,If its a single and TransportKey and a single ValidationKey value (not an array/object is passed) at a time, this is the simplest. Else if object contains objects or inside objects that we want to use or convert to variable, should use a foreach to loop through the object.
//Debuggig
//The string you provided is converted to a json object
//In your case if it is a json object already pass directly it to $j
//below is just for debugging and understanding
//$json='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900","ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
//$j=json_decode($json);
$transkey=$j->CreateTransactionResponse->CreateTransactionResult->TransportKey;
$vkey=$j->CreateTransactionResponse->CreateTransactionResult->ValidationKey;
echo $transkey."</br>";
echo $vkey."<br/>";
/*result as said:
aa900d54-7bfb-47e9-a5de-e423ec34a900
fbb28b32-f439-4801-a434-99c70aa388ca
*/
Related
I need to generate a JSON Object and push it to a JSON object array using PHP.
This is my code.
public function getJSONData()
{
$csv = $this->getCsvData();
$finalArray = array();
// First foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Second foreach to iterate the headlines array.
$newArray = array();
foreach ($csv["headlines"] as $index => $headline) {
// $newArray[$key]->$csv["headlines"] = $value;
// print_r($headline);
// print_r($value[$index]);
// echo " ";
array_push($newArray, array($headline => $value[$index]));
}
echo json_encode($newArray);
echo "<br>";
array_push($finalArray, json_encode($newArray));
}
// dd($finalArray);
}
From this code, I'm getting the following response.
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
But it is not a valid JSON and I really need to get an output like this:
[{"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":639.95}, {"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":509.95}]
This is a standard JSON object array.
In my code, I'm using array_push($newArray, array($headline => $value[$index])); to generate the array and take it as JSON.
Please help me on this.
You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...
// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);
}
echo json_encode($finalArray);
I am querying a service if a person have phone number(s) (also maybe not). I have a json string (as return value) like the following:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
I convert this string to json_decode() function.
$jd = json_decode($json);
Then I want to get the phone numbers only into an array without keys.
if($jd->found) {
$o2a = get_object_vars($json);
}
var_dump($o2a);
When I want to see what $o2a holds with var_dump() function, I get the following:
array (size=2)
'data' =>
array (size=2)
0 =>
object(stdClass)[2]
public 'tel1' => string '1219' (length=4)
1 =>
object(stdClass)[3]
public 'tel2' => string '2710' (length=4)
'found' => boolean true
I want to get only the phone numbers into an array at the end like:
$phones = array('1219', '2710');
What makes me stop doing this is that I do not know how many phone numbers one can have. Json array could consist of more or less elements.
$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found
It may vary 0-to-n, so if it was a constant number I could create that array within a loop.
Some functions without any code :)
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);
Convert it into an array and then you should be able to iterate it easily
$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
foreach($jd['data'] as $key => $val) $phones[] = $val;
}
Instead of handling with an object, use the second parameter of the json_decode function so it would returned an array.
Check if the data and found keys exist.
Since you don't know what are the keys names, you can use array_values
Demo
.
$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
$telArr = $jd['data'];
$phones = array();
foreach($telArr as $tel){
$value = array_values($tel);
$phones[] = $value[0];
}
var_dump($phones);
}
Output:
array(2) {
[0]=>
string(4) "1102"
[1]=>
string(4) "3220"
}
Well, I would try something like that:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
foreach ($jd->data as $key -> $value) {
$phones[] = $value;
}
}
Try as using in_array and simple foreach loop
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
foreach ($arr['data'] as $key => $value) {
foreach($value as $k => $v)
$result[] = $v;
}
}
print_r($result);
Fiddle
I have a simple task that does not work
I Have a json file..
When you decode with the 'true' bool as second param, you will get an associative array back. In your code snippet you then loop it out.
What you should do, is skip the loop and just access the data from the assoc array right away:
echo $array['navn'];
// The JSON object:
{"nr":"5250","navn":"Odense SV","adresser":"http://oiorest.dk/danmark/postdistrikter/5250/adresser"}
// Is equivalent to this php assoc-array:
array("nr" => "5250", "navn" => "Odense SV", "adresser" => "http://oiorest.dk/danmark/postdistrikter/5250/adresser");
try following
<?php
$url = "http://oiorest.dk/danmark/postdistrikter/5000.json";
$content = file_get_contents($url);
$array = json_decode($content, true);
foreach ($array as $key=>$val) {
echo $val;
}
?>
This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach.
Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) )
What I've tried (and which didn't work) was:
$obj = json_decode($arr);
foreach($obj as $data){
echo $data->sql_column->1; //this should echo "value1", but it doesn't
}
Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string.
//First you need to get the string
$json = $arr[0]->sql_column;
//Then decode
$data = json_decode($json);
//Then loop
foreach($data as $key => $value){
echo "$key = $value \n";
}
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner:
foreach($arr as $data){
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
}
I hope you get an idea...
I used foreach for $arr to cover multi values, you can omit that if you want:
$data=$arr[0];
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real or Inter?
For example, if it is json_decoded I can do so:
For Inter:
echo $array['Inter'];
For Real:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()?
json_encode() returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time