fetch array and move array to object in php - php

while ($array = $photo_items->fetch_array()) {
echo $array['img_src'];
echo "<br />";
}
I don't want to use fetch object because I want this array to be within another object.
the current result is 1.jpg2.jpg
what I want is
{
otherproperty: 'something',
img : ['1.jpg'],['2.jpg'];
}
in json

You can do simply, try this way
$json_array = array('otherproperty' => "something", "img" => array())
while ($array = $photo_items->fetch_array()) {
array_push($json_array['img'], $array['img_src'])
}
echo json_encode($json_array);

Related

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

json_encode particular part of array

$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real or Inter?
For example, if it is json_decoded I can do so:
For Inter:
echo $array['Inter'];
For Real:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()?
json_encode() returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time

How do I iterate through an stdObject's array?

Like in Java when you iterate a list, it's real easy, it's like: while(BLAH.hasNext()) { }, so how do I do that in PHP when I have an array within an stdObject that I want to iterate through each and every item?
I keep getting Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 29
<?php
$apiUrl = 'https://api.quizlet.com/2.0/groups/44825?client_id=***BLOCKED FROM PUBLIC***&whitespace=1';
$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($curl);
if ($json) {
$data = json_decode($json);
echo "<h1>Sets from \"{$data->name}\"</h1>";
foreach ($data->sets as $key => $val) {
echo "$key: $val\n";
}
echo "</ul>";
var_dump($data);
}
?>
You can/should use foreach to iterate over every element of an array.
$foo = new stdClass;
$foo->arr = array('1','7','heaven','eleven');
foreach ($foo->arr as $val)
{
if (is_object($val)) var_dump($val);
else echo $val;
}
Note the line I added to var_dump sub-objects. The error you were initially getting was that the elements of your sets array were also objects, not strings as expected. If you only need to access certain elements of the set objects, you can access them using $val->property.
For example you have an object like
$obj = new stdClass;
$obj->foo = 'bar';
$obj->arr = array('key' => 'val', ...);
$array = (array) $obj;
now you can use foreach to iterate over array.
foreach($array as $prop) {
//now if you are not sure if it's an array or not
if(is_array($prop)) {
foreach($prop as $val)
//do stuff
}
else {
//do something else
}
}
The $val variable holds another object (of type stdClass) which contains the details for an individual "set". As you can see, since it generates an error, you cannot echo a stdClass object.
You can access the values inside each object using the object->property notation that you seems to be getting familiar with. For example.
foreach ($data->sets as $set) {
echo $set->title . " by " . $set->created_by . "<br>";
}
/*
An example of the JSON object for a single $set
Access these like $set->title and $set->term_count
{
"id": 8694763,
"url": "http:\/\/quizlet.com\/8694763\/wh-test-1-2-flash-cards\/",
"title": "WH Test 1 & 2",
"created_by": "GrayA",
"term_count": 42,
"created_date": 1323821510,
"modified_date": 1323821510,
"has_images": false,
"subjects": [
"history"
],
"visibility": "public",
"editable": "groups",
}
*/

Categories