Display JSON format data - php

When a retrieve the according data from the database then encode it as json then pass it to the view:
$json_data = json_encode($x);
$search_results['search_results'] = $json_data;
$this->load->view('findquestions',$search_results);
If I display this in the view we get:
[{"question_title":"java"},{"question_title":"big java book"}]
How can the question_titles so "java" be extracted and presented as a url link or inside a table

Since you're passing the json-string directly to the view and then process it (for display) through PHP, you should be able to use PHP's json_decode() to convert it into an object (or array) to use it in a more-friendly manner:
// use json_decode with `true` to get an associative array
$results = json_decode($search_results['search_results'], true);
You can now access the data either directly or within a loop:
// direct access
$title1 = $results[0]['question_title'];
// in a loop
foreach ($results as $result) {
echo 'Title: ' . $result['question_title'];
}
For reference, using the sample-data supplied in the question, a print_r() of the data:
print_r($results);
Array (
[0] => Array (
[question_title] => java
)
[1] => Array (
[question_title] => big java book
)
)

To process the results in PHP
In your controller:
$search_results['search_results'] = $x; //store the array
$this->load->view('findquestions',$search_results); //pass the results as PHP array to view
In your view:
foreach($search_results as $result){
echo $result['question_title'];
}

Related

how to decode std class object

i have a json stored in database which looks like this
[{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"gorilla-preview"}]
i'm retrieving it like this
while($row = mysqli_fetch_assoc($res)){
$array[] = json_decode($row['element']);
}
echo "<pre>";
print_r($array);
its ouput looks like this
Array
(
[0] => Array
(
[0] => stdClass Object
(
[class] => button-input btn btn-warning
[name] => gorilla-preview
[value] => Goat
[id] => gorilla-preview
)
)
)
my question is: how to get all those value in a correct format?
You may have to loop again because you are storing the decoded JSON Data in an Array. So, to fetch the unique values stored in the JSON Object you need a second loop like so:
NOTE: From the Structure of your JSON Data, it seems much obvious that you need a nested Loop though...
<?php
foreach($array as $index=>$arrData){
foreach($arrData as $key=>$objData){
// DO SOMETHING WITH THE INTERNAL VALUES OF THE JSON DATA.
var_dump($objData->class);
var_dump($objData->name);
var_dump($objData->value);
var_dump($objData->id);
}
}
Alternatively, you may (if you so wish) skip storing the data in an Array and use it directly within the first loop like so:
<?php
while($row = mysqli_fetch_assoc($res)){
$objData = json_decode($row['element'][0]);
// DO SOMETHING WITH THE DATA LIKE BUILD A DYNAMICALLY GENERATED HTML STRING.
echo "<p class='{$objData->class}' id='{$objData->id}'>{$objData->value}</p>;
}
UPDATE:
If, according to your comment, you have a JSON Data like: [{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"g‌​orilla-preview"}] the snippet below (which you may Quick-Test Here) shows how you may access your Data:
$json = '[{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"g‌​orilla-preview"}]';
$arrData = json_decode($json);
foreach($arrData as $key=>$objData){
// DO SOMETHING WITH THE INTERNAL VALUES OF THE JSON DATA.
var_dump($objData->class); //<==YIELDS:: string 'button-input btn btn-warning' (length=28)
var_dump($objData->name); //<==YIELDS:: string 'gorilla-preview' (length=15)
var_dump($objData->value); //<==YIELDS:: string 'Goat' (length=4)
var_dump($objData->id); //<==YIELDS:: string 'g‌​orilla-preview' (length=21)
}
Use:
json_decode($row['element'], true);
When you need json_decode to return associated arrays instead of objects just pass true as second parameter.

PHP read file (array) as array

How can I read a json array and add/merge a new element to it?
The content of my file data.json looks like this array:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
new element array example:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
I used explode() and file() but it failed (delimiter for index 1..)..
has someone another idea or it is the right way to solve?
Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().
After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.
Then you may append a new item to that array using [] suffix eg. $a[] = $b;
These three steps are exemplified below.
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode

Setting Assoc Array from Function to use througough page

How would I setup an associative array to reference specific values at different sections of a page. My function:
<?php
function park_data($park_page_id) {
$data = array();
if($park_page_id){
$data = mysql_fetch_assoc(mysql_query("SELECT * FROM `park_profile` WHERE `park_id` = $park_page_id"));
return $data;
}
}
?>
My print_r:
<?php
print_r (park_data(1));
?>
Produces the following associative array:
Array ( [park_id] => 1 [park_name] => Kenai Fjords [park_address] => 1212 4th Avenue [park_city] => Seward [park_state] => Alaska [park_zip] => 99664)
How would I print just the [park_name] value from this array?
From the docs:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
// on PHP 5.4
print_r(park_data(1)['park_name']);
// earlier versions
$tmp = park_data(1);
print_r($tmp['park_name']);
$park=park_data(1);
echo $park['park_name'];
To output custom formatted text in general, and in this case to output only a single array's key value, use echo, because print_r() called on an array displays the whole array's structure and content, and that's not what you want:
<?php
// code
$park_data=park_data(1);
echo $park_data["park_name"];
// code
?>

Php json decode with child

I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.

Referencing a dynamic associative array position

I'm requesting data from an online source which I then decode into json StdClass objects (using php). Once I've done this I have the following (see below). I'm trying to extract the elements in 'otherstuff' by doing echo $response->stuff->WHAT GOES HERE?->otherstuff
However I cant hard code the [2010-12] because its a date, is there any way I can call e.g. $response->stuff->nextsibling->stuff
I hope this makes sense to someone :D Currently i'm bastardising this with a $key => $value for loop and extracting the key value and using it in my $response->stuff->$key->stuff call.
stdClass Object
(
[commentary] =>
[stuff] => stdClass Object
(
**[2010-12]** => stdClass Object
(
[otherstuff] => stdClass Object
(
[otherstuffrate] => 1
[otherstufflevel] => 1
[otherstufftotal] => 1
)
)
)
)
StdClass instances can be used with some Array Functions, among them
current — Return the current element in an array and
key — Fetch a key from an array
So you can do (codepad)
$obj = new StdClass;
$obj->{"2012-10"} = 'foo';
echo current($obj); // foo
echo key($obj); // 2012-10
On a sidenote, object properties should not start with a number and they may not contain dashes, so instead of working with StdClass objects, pass in TRUE as the second argument to json_decode. Returned objects will be converted into associative arrays then.
The date key must be a string, otherwise PHP breaks ;).
echo $response->stuff['2010-12']->otherstuff
Retrieve it using a string.
Edited again: added object code also
json decode it as associative array, and use key fetched through array_keys . See it work here : http://codepad.org/X8HCubIO
<?php
$str = '{
"commentary" : null,
"stuff" : {
"ANYDATE" : {
"otherstuff": {
"otherstuffrate" : 1,
"otherstufflevel" : 1,
"otherstufftotal" : 1
}
}
}
}';
$obj = json_decode($str,true);
$reqKey = array_keys($obj["stuff"]);
$req = $obj["stuff"][$reqKey[0]]["otherstuff"];
print_r($req);
print "====================as object ============\n";
$obj = json_decode($str);
$req = current($obj->stuff)->otherstuff;
print_r($req);
?>

Categories