PHP json decode from database - php

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.

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

Unset all data except the data associated with a given value in url

I have a file that sends a request through curl, when I hit the url which is formatted as http://www.example.com/api/something?id=24 I get a series of arrays back in JSON form. It looks like:
24: {
pe: {
id: "24",
name: "Blah",
engine_src: "blah",
each_lender: "1",
soap_request: "0",
lenders: {
0: "3",
1: "1",
2: "6",
3: "12"
}
},
lenders: {
0: {
id: "1",
platform_id: "2",
lender_id: "3",
engine_id: "24",
status: "1",
engine_lender_id: "3",
engine_lender_name: "choice #1"
},
}
There are several other numbers and arrays in the list that look similar. I need to return the array that is associated with the id in the url and only that array.
I have set a new variable which looks like
$selected = (int)$_REQUEST['pe'];
How do I unset all other values except what is in my $selected variable?
Ok, then, assuming your response is in the variable $jsonresponse...
$selected = json_decode($jsonresponse,$assoc=TRUE);
$selected = $selected[$id];
Thank you for your help Charlene. This is how I ended up solving the problem. It is the same concept that Charlene posted just a slightly different format.
$selected = (int)$_REQUEST['pe'];
$save_me = $data[$selected];
unset($data);
$data = $save_me;
print_r($data);

Excluding numbered-index elements of PDO::fetchAll()

$allrows = $pdo->fetchAll(); // select * from ....
I want to transform this $allrows into JSON by doing :
echo (json_encode($allrowl,JSON_PRETTY_PRINT));
My problem is that this fetchAll will not only extracting data as associate array but also indexed array for each element, hence repeating elements.
[
{
"org_id": "1",
"0": "1",
"category": "A",
"1": "A",
},
{
"org_id": "2",
"0": "2",
"category": "A",
"1": "A",
}
]
Thank you.
That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.
Assuming $pdo is a PDOStatement, set it like this prior to the fetch.
$pdo->setFetchMode(PDO::FETCH_ASSOC);
You can also set it in the fetch statement:
$pdo->fetchAll(PDO::FETCH_ASSOC);
Use PDO::FETCH_ASSOC to get only the associated arrays:
$allrows = $pdo->fetchAll(PDO::FETCH_ASSOC);

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...

Categories