I need PHP JSON help.
I have current output :
{
"status": 200,
"response_msec": 15,
"data": {
"android": {
"test1": 15,
"test2": 6,
"test3": 15,
"test4": 101,
"test5": 87,
"test6": 8,
"test9": 119,
"test10": 101,
"test11": 107
}
}
}
I need print this value : test1 , test2 , test3 ...,test11 .
I have tested some method :
$json = json_decode($result, true);
$dec = (Array)json_decode($result);
print_r ($dec["android"]);
and
foreach ($array as $value)
{
echo $value->android;
}
But not work.
You are missing the ['data'] key,
<?php
$json = '{"status":200,"response_msec":15,"data":{"android":{"test1":15,"test2":6,"test3":15,"test4":101,"test5":87,"test6":8,"test9":119,"test10":101,"test11":107}}}';
$array = json_decode($json, true);
var_dump(array_keys($array['data']['android']));
Check here i have made a php sandbox http://sandbox.onlinephpfunctions.com/code/6f97a9bb499b54919b40d4d12f49049fdd732aef
Also, You can use the function array_keys() to get only the keys of an array, that's what i did.
Your code should work if the json string is assigned to $value. It's just you forgot to include to get the data "data" from "value". Your 3rd line of the first method should look like this:
print_r ($dec["data"]["android"]);
Have a great day
Related
I have 2 different jsons and I need to get one inside the other.
JSON 1
[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]
JSON 2
{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}
I need the second one inside the first one for use with javascript
I tried the array_merge() php function without getting results
since JSON1 is an array of JSON-object and JSON2 is just a JSON-object.
in addition to that you said, 'I need the second one inside the first one for use with javascript'. therefore, you can test this code https://3v4l.org/1HGNF/perf#output
please compare all performances in mem-usage and timing
$j1 = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$j2 = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j1 = json_decode($j1, true);
$j2 = json_decode($j2, true);
$j1[] = $j2;
var_dump(json_encode($j1));
You can use json_decode with parameter true to convert JSON into an array , then use array_merge to make them a single array
$j1 = '[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]';
$j1arr = json_decode($j1, true);
$j2 = ' {
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j2arr = json_decode($j2, true);
$r = array_merge($j1arr[0], $j2arr);
You can use the merged array in javascript by using json_encode
json_encode($r)
https://3v4l.org/WKX1U
Do it simply like this way without any extra array merging methods-
<?php
$json1 = json_decode('[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]',1);
$json2 = json_decode('{"Texto":" VENDO O PERMUTO","imageJob":{"pathConvertido":"ClasificadosPNG/0011311247.png","convertido":true,"id":5011},"rubroClasificado":{"CodigoRubro":150,"id":76}}',1);
$json1[] = $json2; // add second json to first json
print_r($json1);
echo json_encode($json1);
?>
WORKING DEMO: https://3v4l.org/qhsJq
As you said you want to process the resulting data in JavaScript, and as per your question you want second json inside the first json. You can do something like this.
You will get a json as final result.
$first = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$first = str_replace(['[',']','}'], '', $first);
$second = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$second = preg_replace('/\{/', ',', $second,1);
print_r($first.$second);
As result you will get a valid json, second json inside your first json, you can validate here
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have the following JSON code:
{
"google.com": {
"clicks": 23,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
},
"mcnitro.net": {
"clicks": 87,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
}
}
And I am endeavouring to print on the document page the arrays' names and their children.
So far, I have tried the following PHP code:
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data->children() as $domain) {
echo $data[$domain];
foreach($data[$domain] as $value) {
echo $value['clicks'];
}
}
?>
However, I am facing an issue in the error_log:
PHP Fatal error: Call to a member function children() on array in /home/gamin167/public_html/ads/engine/300x250/gen.js.php on line 5
The result wanted was to have "google.com" and "mcnitro.net" printed, as well as their "clicks" property.
Any tip or advice will be highly appreciated! Thanks in advance!
You decode the string to an array with true yet you seem to try and use it as an object.
Also there is no need to loop twice.
foreach($data as $key => $domain) {
echo $key . "\n";
echo $domain['clicks'] . "\n\n";
}
output:
google.com
23
mcnitro.net
87
https://3v4l.org/D7FCY
You cannot use ->children(). $data is an array with your json data, and you can use foreach to get key and value, like foreach ($data as $key => $value).
So here, to get your domain name, just do :
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data as $domain => $value) {
echo $value['clicks'];
}
?>
I only want to display the text from the condition part, see the JSON below
"forecast": {
"forecastday": [
{
"date": "2017-12-01",
"date_epoch": 1512086400,
"day": {
"maxtemp_c": 4.9,
"maxtemp_f": 40.8,
"mintemp_c": 0.9,
"mintemp_f": 33.6,
"avgtemp_c": 1.8,
"avgtemp_f": 35.2,
"maxwind_mph": 9.8,
"maxwind_kph": 15.8,
"totalprecip_mm": 0,
"totalprecip_in": 0,
"avgvis_km": 18,
"avgvis_miles": 11,
"avghumidity": 88,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.apixu.com/weather/64x64/day/116.png",
"code": 1003
},
"uv": 0.5
},
My code shows all the parts from condition, i only want the text part.
See my code below:
$json = json_decode($json, true);
foreach ($json['forecast']['forecastday'] as $forecast) {
echo 'date: '.$forecast['date'].'<br />';
foreach ($forecast['day']['condition'] as $condition) {
echo ''.$condition.'<br />';
}
}
$json = json_decode($json, true);
$counter=0;
foreach ($json['forecast']['forecastday'] as $forecast) {
{ if ($counter++ == 0) continue; }
echo 'date: '.$forecast['date'].'<br />';
echo 'date: '.$forecast['day']['condition']['text'].'<br />';
}
So a bit more explanation about how a multidimensional array works.
Each nested array should be treated-accessed/parsed as a new array. So in your example you have the main array $json , this is where magic starts.
After that in order to reach the text you need to map your array to find the route that will get you there. If you go for
print_r($json)
you will see that you get your whole array. Now you can see that you have to access forecast array first and so you do it like $json['forecast'] and you are inside the nested array. Same logic leads you to day field.
New Edit: This will output your second record only.
I try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.
Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI
Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array
You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!
{
"phone_number": "918358808742",
"confirmation_token": "c86798c29bd811e58f5822000b9964d9",
"experiment_data": {
"opt_in_consent": 7,
"conf_code_auto_submit_ff": 1,
"manual_referral_code_switch": 1,
"conf_code_auto_submit": 1,
"registration_reminders": 1,
"reengagement_gcm_switch": 1,
"kraken_app_progress_meter_v2": 1,
"kraken_background_service_control": 1,
"modified_sms_confirmation_page": 1,
"auto_sms_confirmation": 1,
"registration_express": 1,
"tutorial_before_offer_start": 1,
"fb_connect_active": 1,
"fb_connect_required_for_login": 1,
"auto_sms_confirmation_v2": 1,
"pwd_input_variations": 4,
"registration_reminder_notifications": 1,
"track_adwords_install": 1
},
"member_id": "a2mx2z"
}
I want this data to be in array form any help will be appreciated
You could use json_decode() function, here a simple exmple
$json = {};
$array = json_decode($json, true); // if you would like arrays
$object = json_decode($json); // if you would like object
echo $array['phone_number']; // array example
echo $object->phone_number; // object example
if you would like to test the validation of your json before decode it you can do it using json_encode() function
$json = {};
if(json_encode($json) == false) {
die("incorrect json !");
} else {
// do the decoding
}