PHP Create Multidimension Array for JSON output - php

I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.

You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);

In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);

Related

Generate dynamic html with JSON output (with php)

I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:

How do i retrieve api data using foreach loop in php

This is my data and i want to print the value using decode Json data into array value so please help me out.
{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/",
},
"liked": false
} ] }
I want to retrieve total_results and photos->src->original so how can i do?
First you'll need to use json_decode to converts it into a PHP object:
$response = json_decode($url);
To retrieve total_results:
echo $response->total_results;
You'll have to loop through photos attribute since it's an array of objects:
foreach ($response->photos as $photo) {
echo $photo->src->original;
}
If you have only one object of photos then you can do as below
$obj = '{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/"
},
"liked": false
} ] }';
// Convert JSON string to Array
$objectArray = json_decode( $obj, true );
print_r($objectArray); // Dump all data of the Array
echo $total_results = $objectArray['total_results']; // Access Array data
echo $originalPhoto = $objectArray['photos'][0]['src']['original'];
// For multiple value
if( is_array( $objectArray['photos'] ) && !empty( $objectArray['photos'] ) ){
foreach ($objectArray['photos'] as $photo) {
echo $photo['src']['original'];
}
}

Accessing Data in Array - Non-Object Error PHP

I'm populating an array like this:
$POarray = array();
foreach($orders as $order)
{
$total = OrderItems::where('OrderID', $order->OrderID)->sum('TotalPrice') * (1 + $LRmarkup);
$arraydata = array(
'Name' => $order->OrderNumber,
'Total' => $total);
$POarray[] = $arraydata;
}
This results in the contents of the $POarray variable being:
[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]
I am attempting to access this data like this:
$purchase1name = $POarray[0]->Name;
$purchase1total = $POarray[0]->Total;
And I am getting this error:
"Trying to get property of non-object"
Shouldn't this work?
Thank you for taking the time to respond.
$POarray is not an object.
Try:
$purchase1name = $POarray[0]['Name'];
$purchase1total = $POarray[0]['Total'];
You need to do this way after decoding it using json_decode(),
<?php
$key='[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]';
$POarray = json_decode($key);
echo $POarray[0]->Name;
echo $POarray[0]->Total;
?>
DEMO: https://3v4l.org/JvCam
You can also use this.
array_get($POarray[0], 'Name');
array_get($POarray[0], 'Total');
For more information: https://laravel.com/docs/5.7/helpers

PHP Save nested json to mysql database

I have some json data that i am retrieving from an external url. It is not importing correctly unless i take out some of the brackets. Anyone know how to properly import this json data? I don't really need the "success", "num_items", "build time" and "updated at". Im a noobie. Thanks!
Here is the php
$filename = "http://www.someurl.com/data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_items(name, quality) VALUES (
'".$row["name"]."',
'".$row["quality"]."'
)";
mysqli_query($connect, $sql);
}
Here is data.json
{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}
You were looping through the wrong element of your array.
As you want to list the items, your loop must look like :
foreach($array["items"] as $row)
//$filename = "http://www.someurl.com/data.json";
//$data = file_get_contents($filename);
$data='{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}';
$array = json_decode($data, true);
$sql = "INSERT INTO table_all_items(name, quality) VALUES ";
foreach($array["items"] as $row)
{
$sql = $sql." (
'".$row["name"]."',
'".$row["quality"]."'
),";
}
mysqli_query($connect, substr($sql,0,-1));
I also updated the sql query, for it sends only one request with many values, instead on many requests with one value.

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>

Categories