how to decode std class object - php

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.

Related

PHP Array - Array Returns Value, And a 0

So I got this array:
$list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');
if($list) {
$data = array('firmware' => $list->region->system_pup[0]['label']);
header('Content-Type: application/json');
echo json_encode($data);
}
And it outputs this:
{"firmware":{"0":"5.01"}}
But there's also a zero there. How do I remove it from the array so it's like this:
{"firmware":"5.01"}
This is a SimpleXMLElement result which you need to convert to a string if you want that data:
$data = array('firmware' => (string) $list->region->system_pup[0]['label']);
In JSON form it looks like an associative array, which it isn't, so the [0] trick which normally works to navigate to it won't.

delete an element of given key of array in php

$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // here output like this => [{"name":"abc","email":"abc#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2","email":"abc2#email.com"}]
unset($responseAry[1]);
echo "------------removed 1--------";
echo json_encode($responseAry); // but here output like this => {"0":{"name":"abc","email":"abc#email.com"},"2":{"name":"abc2","email":"abc2#email.com"}}
I want Out put Like this after removing an element \n [{"name":"abc","email":"abc#email.com"},{"name":"abc2","email":"abc2#email.com"}]
Please Help me
Try to regenerate your array after unset an item:
$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"abc2#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2"}]__
unset($responseAry[1]);
$responseAry = array_values($responseAry); //regenerate array(reindexing)
echo "------------removed 1--------";
echo json_encode($responseAry); //[{"name":"abc","email":"abc#email.com"},{"name":"abc2","email":"abc2#email.com"}]
EDIT:
As other option you can use array_splice method http://php.net/manual/en/function.array-splice.php
$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"abc2#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2"}]__
array_splice($responseAry,1,1);
echo "------------removed 1--------";
echo json_encode($responseAry);
Your array when first converted to json is a so called "associative" array, and json_encode then exports it to the object you see in the first echo.
After your unset, the array is changed to a "numeric" array and json_encode will export the array with array keys.
Php it self does not care about how the array is used, but json_encode does.
You can use
echo json_encode(array_values($responseAry));
Or not change the final array you want to export

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.

Display JSON format data

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'];
}

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