How to write SELECT query in mysql json Array data - php

I am trying to get the email from the array json, but it returns null value
[
{
"name": "Arun",
"email": "arun#arun.com"
},
{
"name": "Arun kumar",
"email": "arunkumar#gmail.com"
}
]
and my Json query is select json->>"$.name" as email from json
But this query is return null value

I tested the following and worked for me on your json sample
$json='[{"name": "Arun", "email": "arun#arun.com"}, {"name": "Arun kumar", "email": "arunkumar#gmail.com"}]';
$data=json_decode($json,true);
foreach ($data as $key => $value) {
echo $value["email"] . "<br>";
}

This should work,
JSON_EXTRACT(yourstring, '$[*].email')
yourstring - your json data or field in database
$ is json syntax to search json object
* means all multidimensional array
email check email in * values

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

Form Table out of JSON Array

I've got a simple question.
I'm getting a PHP Array from a mysql query and I encoded it so it looks like this:
[
{
"ID": "111111",
"JoinDate": "2015-05-13",
"Nickname": "TestUser1"
},
{
"ID": "222222",
"JoinDate": "2015-05-06",
"Nickname": "TestUser2"
},
{
"ID": "333333",
"JoinDate": "2000-01-01",
"Nickname": "TestUser3"
}
]
How can I iterate through this Array and Form a simple HTML Table?
Heres an example of outputting array elements in table rows.
foreach ($elements as $element) {
echo '<tr><td>'. $element['ID'].'</td><td>>'. $element['Nickname'].'</td></tr>';
}

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

PHP json decode from database

I have this json encode in the database, and i want just echo values name_r in foreach , how is it?
[{
"name_r": "saeed",
"units": ["salam", "11", "11", "khobe", "22", "22", "salam"],
"price_change": ["33", "33", "33", "44", "44", "44"]
}, {
"name_r": "salavat",
"units": ["55", "55", "khobe", "66", "66"],
"price_change": ["77", "77", "77", "88", "88", "88", "99", "99", "99"]
}]
this my php, that have error(Message: Undefined index: name_r - Line Number: 179):
$query = $this->db->query("SELECT * FROM table ORDER BY id desc");
$data = array();
foreach ($query->result() as $row)
{
$data[] = json_decode($row->residence,true);
echo $data["name_r"].'<br>'; //Line Number: 179
}
Assuming that the json_encoded data you provided is stored in one row of the database, the json_decode will give you an array of arrays. To echo all the name_r fields, you would need to:
foreach ($query->result() as $row){
$data = json_decode($row->residence,true);
foreach($data as $datum){
echo $datum['name_r'];
}
}
You used [] in your assignment. This means that the result of the json_decode will be pushed at the end of your array.
Using var_dump($data) should help you understand what your array actually looks like, and solve your problem by yourself.
Assuming the example JSON you showed is data from a single record. The data is an array of objects, so you'll need an inner loops that loops over the array from each returned record.
foreach ($row->residence as &$value) {
$data = json_decode($value,true);
echo $data["name_r"].'<br>';
}
I am not a PHP dev, so I am unsure if my syntax is right. But hopefully you get the idea.

Categories