I got these Json data:
[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]
With Javascript I have successfully managed data to present as follow:
Pizza
-Beef Pronto: Description of Beef Pronton here: 12
Drink
-Cool Delight: Description of Coold Delight here: 5
-Cola: Description of Cola: 4
any Idea how to do it with PHP ?
-->Ok guys, this is How I do it with PHP:
<?
$listedmenuJSON = '[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]';
$json_decoded = json_decode($listedmenuJSON);
foreach ($json_decoded as $categoryvalue){
//echo $categoryvalue->category."<br/>";
$tempcategoryvalue[] = $categoryvalue->category;
$arrunique = array_unique($tempcategoryvalue);
}
foreach ($arrunique as $tmpcategory){
echo '<br/><b>'.$tmpcategory.'</b></br>';
foreach ($json_decoded as $tempo){
if($tempo->category == $tmpcategory){
echo $tempo->name.'<br/>';
echo '<i>'.$tempo->desc.'.......</i>';
echo $tempo->price.'<br/>';
}
}
}
?>
It will generate as following:
Pizza
Beef Pronto
Description of Beef Pronton here.......12
Drink
Cool Delight
Description of Coold Delight here.......5
Cola
Description of Cola.......4
If you got json in PHP Code Use Following line to convert json to PHP array and manipulate array for desire output
$array = json_decode($json,TRUE);
In javascript user below code to convert your json to array.
var obj = jQuery.parseJSON(responce);
Try using the PHP function 'json_decode' (http://php.net/manual/en/function.json-decode.php). This will create an associative array in PHP. It should be pretty simple to access and manipulate data thereon.
If you use a SQL server then you can select form the table using "group by category"
Else, you can just verify many times the arrays.
SQL:
<?php
$query = "SELECT * FROM 'table'
GROUP BY category
having (category=\"Pizza\");"
--SELECT * FROM 'table'
--GROUP BY category
--having (category="Drink");
if you use this in php you must use sql_query("query")
Related
This question already has answers here:
How to parse JSON and access results
(3 answers)
Closed last month.
i have this type of data store in mysql, how can i echo only the amount value from this?
{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}
this code looks like json data, if yes then should i be using jquery to echo the values or is there a way to do it in php?
You can use the json_decode function to turn it into a PHP object and then access its properties. For your example, you can do this to get the "amount" property:
<?php
$js='{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}';
echo json_decode($js)->{"1"}->amount;
?>
$data = json_decode('{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}');
Ex1: ((array) $data)[1]->amount
Ex2: $data->{'1'}->amount]);
Try this
$json_string = '{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}';
$json_data = json_decode($json_string, TRUE);
I am querying 3 tables in PostgreSQL and converting the result into a nested json object. I am using PHP (and the Slim framework) as my application code. I am able to return a valid nested JSON object using PostgreSQL's built-in json operators. However, I'm having trouble rendering that JSON object in PHP.
PHP's json_encode operator seems to be trying to perform a JSON conversion on the provided obect (which is already in JSON format). And I can't get PHP to simply echo, print (or print_r) out the valid result provided by PostgreSQL. PHP keeps adding extra characters to the result.... I've tried :
(a) not using the PostgreSQL JSON operators,
(b) using PHP's json_decode before using json_encode,
(c) simply running echo and print_r statements, and
(d) I just started toying with using str_replace to remove the extraneous characters, but that is starting to feel scuzzy...
I'm pretty sure I'm doing something obviously wrong. I'm just at a standstill on this one. Any help is greatly appreciated!
The 3 tables are :
1. Company
2. Contact
3. Pic
CONTACT >----(:company_id)----- COMPANY ----(:company_id)-----< PIC
(A single company can have many contacts, and can have many pics... No relationship b/w the CONTACT and PIC tables)
HERE IS THE PHP CODE WHICH USES THE POSTGRESQL QUERY :
<?php
$app->get('/companies/{id}', function($request)
{
$db = pg_connect("host=localhost dbname=cool_db_name user=postgres")
or die('Could not connect: ' . pg_last_error());
$id = $request->getAttribute('id');
$query = "
SELECT row_to_json(t)
FROM (
SELECT company_id, company_name, company_street, company_city, company_state, company_zip, active_ind
, (
SELECT array_to_json(array_agg(row_to_json(c)))
FROM (
SELECT ct.contact_id, ct.contact_lname, ct.contact_fname, ct.contact_email, ct.active_ind
FROM contact ct
WHERE ct.company_id = c.company_id
ORDER by ct.contact_lname
) c
) AS contacts
, (
SELECT array_to_json(array_agg(row_to_json(p)))
FROM (
SELECT p.pic_id, p.pic_location, p.active_ind
FROM pic p
WHERE p.company_id = c.company_id
AND p.active_ind = 1
ORDER by p.pic_id
) p
) AS pics
FROM company c
WHERE c.alive_ind = 1 AND c.company_id = " . $id . "
) t
;";
$result = pg_query($db, $query);
while($row = pg_fetch_assoc($result))
{
$data[] = $row;
}
if(isset($data))
{
header('Content-Type: application/json');
echo json_encode($data);
}
});
1. Again, if I run that PostgreSQL query by itself, the result is VALID JSON (below) :
{
"company_id": 1,
"company_name": "Company #1",
"company_street": "111 Fun Ave",
"company_city": "Creve Coeur",
"company_state": "MO",
"company_zip": "10002",
"active_ind": 1,
"contacts": [{
"contact_id": 1,
"contact_lname": "Figgis",
"contact_fname": "Cyril",
"contact_email": "figgis#gmail.com",
"active_ind": 1
}, {
"contact_id": 2,
"contact_lname": "Kane",
"contact_fname": "Lana",
"contact_email": "lana#gmail.com",
"active_ind": 1
}, {
"contact_id": 3,
"contact_lname": "Tunt",
"contact_fname": "Cheryl",
"contact_email": "crazy#gmail.com",
"active_ind": 1
}],
"pics": [{
"pic_id": 1,
"pic_location": "profile/pic_900.jpg",
"active_ind": 1
}, {
"pic_id": 2,
"pic_location": "profile/pic_901.jpg",
"active_ind": 1
}, {
"pic_id": 3,
"pic_location": "profile/pic_902.jpg",
"active_ind": 1
}, {
"pic_id": 4,
"pic_location": "profile/pic_903.jpg",
"active_ind": 1
}]
}
(sorry for the poor formatting... it looks better in jsonlint.com)
2. ...but when I run that same query in the PHP application I get the following result (WEIRD JSON) :
[{"row_to_json":"{\"company_id\":1,\"company_name\":\"Company #1\",\"company_street\":\"111 Fun Ave\",\"company_city\":\"Creve Coeur\",\"company_state\":\"MO\",\"company_zip\":\"10002\",\"active_ind\":1,\"contacts\":[{\"contact_id\":1,\"contact_lname\":\"Figgis\",\"contact_fname\":\"Cyril\",\"contact_email\":\"figgis#gmail.com\",\"active_ind\":1},{\"contact_id\":2,\"contact_lname\":\"Kane\",\"contact_fname\":\"Lana\",\"contact_email\":\"lana#gmail.com\",\"active_ind\":1},{\"contact_id\":3,\"contact_lname\":\"Tunt\",\"contact_fname\":\"Cheryl\",\"contact_email\":\"crazy#gmail.com\",\"active_ind\":1}],\"pics\":[{\"pic_id\":1,\"pic_location\":\"profile/pic_900.jpg\",\"active_ind\":1},{\"pic_id\":2,\"pic_location\":\"profile/pic_901.jpg\",\"active_ind\":1},{\"pic_id\":3,\"pic_location\":\"profile/pic_902.jpg\",\"active_ind\":1},{\"pic_id\":4,\"pic_location\":\"profile/pic_903.jpg\",\"active_ind\":1}]}"}]
Like I said, I'm at a loss right now. Any help would be GREATLY appreciated. Thanks!
So, using that last escaped data format, you could do:
$noSlahes = str_replace("\", "", $yourEscapedJsonString);
This removes the slashes, replacing them with nothing. Now:
$jsonObject = json_decode($noSlahes);
Then, select rowToJson for it to be identical to your properly formatted JSON:
echo $jsonObject->row_to_json;
If someone else hits this problem and finds this question, both of the suggested answers are not an answer but a dirty workaround. The real problem lays on the query at the beginning and not on the php side.
Don't use ARRAY_AGG(ROW_TO_JSON())
Don't wrap any JSON function of PostgreSQL in ARRAY_AGG(), which will convert the JSON into a PostgreSQL Array and effectively will brake the JSON format escaping the quotes. A PosgreSQL array is not a JSON or a PHP array.
Use instead JSON_AGG()
The right aggregation function of JSON objects returned by any PostgreSQL JSON function like ROW_TO_JSON, JSON_BUILD_OBJECT etc, is done using JSON_AGG() function.
header('Content-Type: application/json');
$noSlashes = str_replace("\\","",$data); /* no need for json_encode() */
$hope = array_values($noSlashes[0]);
foreach($hope as $key => $value)
{
print $value;
}
Using PHP, I'm looking to get an id passed via the url and then lookup some data in a JSON file... then display the data back on the page.
I'll set up the url to be http://mytestapp.php?id=12345678 and then use;
$id = $_GET['id'];
to set the id variable. I then have a JSON as below;
{
"ads":
[
{ "id":"12345678",
"hirername":"Test Hirer",
"hirercontact":"Rob A",
"role":"Ultra Sat Role",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"John Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jack Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
},
{ "id":"12345679",
"hirername":"Test Hirer 2",
"hirercontact":"Jesse S",
"role":"Ultra Sat Role 2",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"Jill Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jenny Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
}
]
}
Which i want to search for the id, and then be able to echo the contents of the data out.
I'm reading the JSON and decoding into an array as such;
$json = file_get_contents('data.json');
$arr = json_decode($json, true);
But i'm not sure how to now read the array, find the data i want based on the id, and then pull out the data so i can display it on the page as follows;
Hirer: Test Hirer
Contact: Rob A
Role: Ultra Sat Role
Requirements:
- Right to work in Australia
- Live Locally
John Smith Nunawading (23km away)
Pizza maker at Don Domenicos for 4 years
Bakery Assistant at Woolworths for 4 years
Mon to Fri | Morning, Evening & Night
0413451007
Jack Smith Endeadvour Hills (35km away)
Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year
Mon to Fri | Morning & Evening
041345690
Any ideas?
Thanks Rob.
Borrowed the example from #RobbieAverill and modified to suit your needs, please check if this works.
<?php
$id = $_GET['id'];
$json = file_get_contents('data.json');
$foundAd = null;
$json = json_decode($json,true);
foreach ($json['ads'] as $ad) {
if ($ad['id'] == $id) {
$foundAd = $ad;
break;
}
}
echo "Hirer:".$foundAd['hirername']."<br/>";
echo "contact:".$foundAd['hirercontact']."<br/>";
echo "role:".$foundAd['role']."<br/><br/>";
echo "Requirements<br/>";
echo "<ul>";
foreach($foundAd['requirements'] as $req){
echo "<li>".$req['req']."</li>";
}
echo "</ul><br/>";
foreach($foundAd['candidates'] as $req){
echo $req['name']." ". $req['dist']."</br>";
echo $req['exp1']."</br>";
echo $req['exp1']."</br>";
echo $req['avail1']."</br>";
if($req['avail2']!=""){
echo $req['avail2']."</br>";;
}
echo $req['call']."</br></br>";
}
?>
In your current inplementation you need to loop over all the ads objects like
foreach ($arr['ads'] as $ad){
if ($ad['id'] == $id){
//do stuff;
}
}
A better implementation would be to use the value of the id as the key of the json object when you store the json. Using something like
$ads[id] = $yourjsonobject;
Then referencing would just be $arr['ads'][id];.
You can then use multiple foreach or if your keys are knows just use the keys to output the object you need like
echo $ad["hirername"];
Using the foreach loop to print the complete object:
foreach( $ad as $value){
print_r($value);
}
I have a table that has a field that contains what appears to be an array in it. Is there an easy way to convert this into an array that I can work with?
SELECT data FROM exp_cartthrob_item_options_options
Print_r(data);
Returns the following:
a:19:{i:0;a:6:{s:12:"option_value";s:18:"cp-1202-faraglioni";s:11:"option_name";s:16:"1202 Faraglioni ";s:5:"price";s:0:"";s:5:"color";s:5:"Putty";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:1;a:6:{s:12:"option_value";s:21:"cp-1203-scala-fenicia";s:11:"option_name";s:18:"1203 Scala Fenicia";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:2;a:6:{s:12:"option_value";s:19:"cp-1204-castiglione";s:11:"option_name";s:17:"1204 Castiglione ";s:5:"price";s:0:"";s:5:"color";s:5:"Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:3;a:6:{s:12:"option_value";s:19:"cp-1205-villa-jovis";s:11:"option_name";s:17:"1205 Villa Jovis ";s:5:"price";s:0:"";s:5:"color";s:3:"Tan";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:4;a:6:{s:12:"option_value";s:16:"cp-1207-anacapri";s:11:"option_name";s:14:"1207 Anacapri ";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:5;a:6:{s:12:"option_value";s:20:"cp-1208-monte-solaro";s:11:"option_name";s:17:"1208 Monte Solaro";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:6;a:6:{s:12:"option_value";s:13:"cp-BLCK-black";s:11:"option_name";s:10:"BLCK Black";s:5:"price";s:0:"";s:5:"color";s:6:"Black ";s:13:"grain_texture";s:5:"Full ";s:6:"finish";s:5:"Light";}i:17;a:6:{s:12:"option_value";s:21:"cd-0061-mexican-ochre";s:11:"option_name";s:18:"0061 Mexican Ochre";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:18;a:6:{s:12:"option_value";s:12:"cd-0063-soho";s:11:"option_name";s:9:"0063 SoHo";s:5:"price";s:0:"";s:5:"color";s:6:"Orange";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:19;a:6:{s:12:"option_value";s:13:"cd-0064-cocoa";s:11:"option_name";s:10:"0064 Cocoa";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:20;a:6:{s:12:"option_value";s:18:"cd-0065-brownstone";s:11:"option_name";s:15:"0065 Brownstone";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:21;a:6:{s:12:"option_value";s:13:"cd-0066-tabac";s:11:"option_name";s:10:"0066 Tabac";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:22;a:6:{s:12:"option_value";s:18:"cd-0067-toro-black";s:11:"option_name";s:15:"0067 Toro Black";s:5:"price";s:0:"";s:5:"color";s:5:"Black";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:23;a:6:{s:12:"option_value";s:23:"cd-0068-sun-dried-brick";s:11:"option_name";s:20:"0068 Sun-Dried Brick";s:5:"price";s:0:"";s:5:"color";s:12:"Medium Brown";s:13:"grain_texture";s:5:"Full ";s:6:"finish";s:5:"Light";}i:24;a:6:{s:12:"option_value";s:14:"cd-0069-gothic";s:11:"option_name";s:11:"0069 Gothic";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:25;a:6:{s:12:"option_value";s:23:"cd-0070-rembrandt-brown";s:11:"option_name";s:23:"0070 Rembrandt Brown ";s:5:"price";s:0:"";s:5:"color";s:12:"Medium Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:27;a:6:{s:12:"option_value";s:15:"cd-0078-pompeii";s:11:"option_name";s:12:"0078 Pompeii";s:5:"price";s:0:"";s:5:"color";s:3:"Red";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:30;a:6:{s:12:"option_value";s:21:"cd-0082-gulmard-green";s:11:"option_name";s:18:"0082 Gulmard Green";s:5:"price";s:0:"";s:5:"color";s:10:"Dark Green";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:31;a:6:{s:12:"option_value";s:21:"cd-0084-prussian-blue";s:11:"option_name";s:18:"0084 Prussian Blue";s:5:"price";s:0:"";s:5:"color";s:9:"Dark Blue";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}}
Yes, you can use unserialize() to achieve that:
SELECT data FROM exp_cartthrob_item_options_options
$array = unserialize($data);
var_dump($array);
I have the following MySQL table structure:
num field company phone website
1 Gas abcd 123456789 abcd.com
2 Water efgh 987654321 efgh.com
3 Water ijkl 321654987 ijkl.com
4 Heat mnop 987654321 mnop.com
5 Gas qrst 123789654 qrst.com
...
Is it possible with PHP (maybe using some mixture of GROUP_BY and ORDER_BY) to echo the data to the screen in the following format:
Gas:
abcd qrst
123456789 123789654
abcd.com qrst.com
Water:
efgh ijkl
987654321 321654987
efgh.com ijkl.com
Heat:
mnop
321654987
mnop.com
The exact format of it isn't important. I just need for the different rows of data to be listed under the appropriate field with none of the fields repeated. I've been trying to figure this out for a while now, but I'm new to PHP and I can't seem to figure out how to do this, if it's even possible, or if there's a better way to organize my data to make it easier.
To avoid performing a "Gas" query, a "Water" query and a "Heat" query, you could order the results by "field" and then handle the display in PHP...
SELECT
Field,
Company,
Phone,
Website
FROM
tblYourTable
ORDER BY
Field
In your PHP loop, you would need to keep tabs on your current "Field" and start a new list when it changes. For example:
$CurrentField = '';
... loop
if ($MyData->Field != $CurrentField) {
$CurrentField = $MyData->Field;
....
}
... end loop
I will assume that you know how to retrieve MySQL data into an array... so, we have:
[0] {
num => 1,
field => "Gas",
company => "abcd",
phone => "123456789",
website => "abcd.com"
}
[1] ... (so on)
Then create a loop like:
foreach($data as $row) {
$service = $row["field"]; //Water, Gas, etc...
unset($row["field"]); //do not add this
foreach($row as $key => $value) {
$field[$service][$key][] = $value;
}
}
The resulting array will be something like:
$field["Gas"]["company"][0] = "abcd";
$field["Gas"]["company"][1] = "qrst";
$field["Water"]["company"][0] = "efgh";
...
$field["Gas"]["phone"][0] = "123456789";
$field["Gas"]["phone"][1] = "123789654";
$field["Water"]["phone"][0] = "987654321";
...
In that way you can then generate the output:
foreach($field as $service => $infoarr) {
echo $service."\n";
foreach($infoarr as $info => $datarr) {
foreach($datarr as $datum) {
echo $datum."\t";
}
echo "\n";
}
echo "\n";
}
Theorically (untested) will output:
Gas
abcd qrst
123456789 123789654
Water
efgh ...
I hope you find it useful... There should be a better way, but I didn't thought
too much about it...