JSON Decode not showing all data PHP - php

I am trying to decode a JSON file in PHP (which I do all the time). But when I try and use this file: https://www.hyzyne.co.nz/updatewlg/nzta.json . It decodes it but then only shows the last part of the JSON in the array.
PHP:
$xml = file_get_contents('https://www.hyzyne.co.nz/updatewlg/nzta.json');
$data = json_decode($xml, true);
print_r($data);
If you view the file you will see it is quite long.
When I print the above all I get is:
Array ( [data] => Array ( [0] => Array ( [roadevent] => Array ( [alternativeRoute] => Follow Detours [directLineDistance1] => 1.55 km southeast of Taradale [directLineDistance2] => 1.62 km southwest of Jervoistown [directLineDistance3] => 1.66 km east of Waiohiki [endDate] => 2013-12-03T18:25:18.677+13:00 [eventComments] => Now Clear [eventDescription] => Crash [eventId] => 84295 [eventIsland] => North Island [eventType] => Road Hazard [expectedResolution] => Until further notice [impact] => Caution [locationArea] => SH 50 Taradale [locations] => Array ( [location] => 050-0005/04.88 Taradale ) [planned] => false [startDate] => 2013-12-03T17:17:00.000+13:00 [status] => Resolved [wktGeometry] => SRID=27200;POINT (2841479.57385071 6176775.805777006) [eventCreated] => 2013-12-03T17:20:18.450+13:00 [eventModified] => 2013-12-03T18:25:18.380+13:00 [informationSource] => Police [supplier] => Official [eventRegions] => Array ( [eventRegion] => Taranaki, Manawatu-Wanganui, Hawke's Bay & Gisborne Region ) ) ) ) )
Which is not all of the JSON, I did make the JSON file myself. But I am unable to recognise any problems in the JSON.
Even when putting my JSON through http://jsonlint.com/ I only get the last segment. Does anyone know what I am doing wrong?
Thanks

You have an issue with your json. You are repeating the property "roadevent". I'm assuming they all shouldn't be contained in the same object { inside the array [.
{
"data": [{
"roadevent": {
"alternativeRoute": "Local Roads",
"directLineDistance1": "1.43 km west of Heathcote Valley",
"directLineDistance2": "1.45 km southwest of Ferrymead",
"directLineDistance3": "1.68 km southwest of Mount Pleasant",
"eventComments": "Bridges Not To Be Crossed By Any Overweight Loads Except For Iso Containers Being Moved On Existing Overweight Permits. Any Other Overweight Loads (including Those Travelling On Area Permits) Will Be Considered On A Case By Case Basis.",
"eventDescription": "Other",
"eventId": "47078",
"eventIsland": "South Island",
"eventType": "Road Hazard",
"expectedResolution": "Until further notice",
"impact": "Vehicle Restrictions",
"locationArea": "SH 74 Christchurch - Tunnel Rd, Horotane Valley Overpasses No 1 And 2 (bsn 217 & 218)",
"locations": {
"location": "074-0019/02.60-D Heathcote Valley"
},
"planned": "false",
"restrictions": "Road constricted for oversize and non-standard vehicles",
"startDate": "2011-03-03T17:47:00.000+13:00",
"status": "Active",
"wktGeometry": "SRID=27200;POINT (2485362.087794318 5737151.779842964)",
"eventCreated": "2011-03-03T17:49:29.260+13:00",
"eventModified": "2012-08-15T17:52:54.210+12:00",
"informationSource": "NMC",
"supplier": "Official"
},
"roadevent": {
"alternativeRoute": "-",
"directLineDistance1": "0.69 km southwest of Hakataramea",
"directLineDistance2": "0.92 km northeast of Kurow",
"directLineDistance3": "6.43 km southeast of Lake Waitaki",
"eventComments": "Speed Restriction In Place For Heavy Vehicles Of 20kph.",
"eventDescription": "Other",
"eventId": "62595",
"eventIsland": "South Island",
"eventType": "Road Hazard",
"expectedResolution": "Until further notice",
"impact": "Caution",
"locationArea": "SH 82 Waitaki River Bridge No 1 ( Kurow Bridges)",
"locations": {
"location": "082-0053/16.68 -"
},
"planned": "false",
"startDate": "2012-06-14T12:17:00.000+12:00",
"status": "Active",
"wktGeometry": "SRID=27200;POINT (2310306.0879597953 5605922.516155325)",
"eventCreated": "2012-06-14T12:17:55.127+12:00",
"eventModified": "2012-08-15T17:46:26.197+12:00",
"informationSource": "NMC",
"supplier": "Official"
},

just replace ,"roadevent": to ,
JSON ending Gisborne Region"}}]}}
JSON starting {"data":{"roadevent":[{"alternativeRoute"

Related

Cant get ipaddr with TheNetworg/oauth2-azure Resource Owner

I am using a PHP Library TheNetworg/oauth2-azure
Would like to seek help getting ipaddr from access_token;
I cant seem to get the ipaddr with $resourceOwner -> claim("ipaddr");
our company is using API Gateways which is why I cannot use the client IP for IP Address;
here's the print_r($resourceowner);
TheNetworg\OAuth2\Client\Provider\AzureResourceOwner Object (
[data:protected] => Array ( [aud] =>
73b99a0d-33db-4f60-9428-246ab79ad7a1 [iss] =>
https://login.microsoftonline.com/f3211d0e-125b-42c3-86db-322b19a65a22/v2.0
[iat] => 1654196670 [nbf] => 1654196670 [exp] => 1654200570
[auth_time] => 1653645878 [email] => adolf.rey.a.along#domain.com
[name] => Along, AR [oid] => a3d7f1ef-4b90-40bb-bb98-0b231fc3190c
[preferred_username] => adolf.rey.a.along#domain.com [rh] =>
0.ASYADh0h81sSw0KG2zIrGaZaIg2auXPbM2BPlCgkarea16EmAFA. [sub] => 7nrl5r4ZBgwsywvLVuRMiKCj40P_ABRbbh8Qg0WRJR4 [tid] =>
f3211d0e-125b-42c3-86db-322b19a65a22 [uti] => x-Nzcykiq0a1zqiW2sAAAA
[ver] => 2.0 ) )
here is what I get from jwt.io with the access token:
{
"aud": "https://graph.microsoft.com",
"iss": "https://sts.windows.net/f3211d0e-125b-42c3-86db-322b19a65a22/",
"iat": 1654192709,
"nbf": 1654192709,
"exp": 1654198372,
"acct": 0,
"acr": "1",
"acrs": [
"urn:user:registersecurityinfo",
"c1",
"c2"
],
"aio": "AVQAq/8TAAAAx1MCI+PyDFrMZwtwqaEKGKzGscUtn9R3OhpGGaZozsW7yPFJMfadAR4UgOc485j73E38OdNa3wu7FwLqxBeiZBnC7E3wXAX4Y1//zzZK6D4=",
"amr": [
"pwd",
"mfa"
],
"app_displayname": "7107_MYAPP_LEGACY_PHP_Staging_ESOPortal",
"appid": "73b99a0d-33db-4f60-9428-246ab79ad7a1",
"appidacr": "1",
"family_name": "Along",
"given_name": "Adolf Rey",
"idtyp": "user",
"ipaddr": "112.202.179.1",
"name": "Along, AR",
"oid": "a3d7f1ef-4b90-40bb-bb98-0b231fc3190c",
"onprem_sid": "S-1-5-21-861567501-413027322-1801674531-3036785",
"platf": "3",
"puid": "1003BFFD8DC81D0E",
"rh": "0.ASYADh0h81sSw0KG2zIrGaZaIgMAAAAAAAAAwAAAAAAAAAAmAFA.",
"scp": "email openid profile User.Read",
"signin_state": [
"kmsi"
],
"sub": "-ePe17Ssg1rFUWAE_u1Sn5_7Kr5IYaCnccVRtaU1euE",
"tenant_region_scope": "NA",
"tid": "f3211d0e-125b-42c3-86db-322b19a65a22",
"unique_name": "adolf.rey.a.along#domain.om",
"upn": "adolf.rey.a.along#domain.com",
"uti": "cycwWq1hrEK3gjBdx03IAA",
"ver": "1.0",
"wids": [
"b79fbf4d-3ef9-4689-8143-76b194e85509"
],
"xms_st": {
"sub": "7nrl5r4ZBgwsywvLVuRMiKCj40P_ABRbbh8Qg0WRJR4"
},
"xms_tcdt": 1403205942
}

How To Seperate STATE, CITY and ZIPCODE when cases are change

I found the same question but that's not very helpful because that is not working in many cases. So, I'm writing this question may be somebody have a better solution for it.
These are my addresses example.
[0] => "Skattkarr Varmland SE-65671" //Sweden
[1] => "Rayleigh , Essex SS6 8YJ" //UK
[2] => "Horgen, Zürich 8810" //Switzerland
[3] => "Edmonton Alberta T5A 2L8" //Canada
[4] => "REDDING, CA 96003" //USA
[5] => "New York, NY 96003" //USA
[6] => "New York NY 96003" //USA
I tried alot, but for many cases I'm getting failed.
I can pass 2 or 3 but I can't pass for all. Especially when the the country changes.
I tried to explode(" ",$addr[0]), it giving me the state on 0 and city on 1, but I try to use explode(" ",$addr[6]), It will give me New as a state and York as city. And same for UK and Canada zip code will be wrong.
My last question was marked duplicate, but my query is different and This question does not help me.
In order to separate these strings into state city and zipcode, you will need to define rules that can apply to all of your strings.
If we separate them by space, New York is not gonna work since New York is a city but has space in the middle.
If we separate them by comma, some of them don't have comma.
If we separate by both space and comma, we cannot assume the last item will be zipcode since T5A 2L8 is zipcode but will be separated.
So there is no rule that I can think of that would work with your data. You should start from how these strings can be separated and identified. Try to apply it to the code and we will gladly help you.
I tried to use OSM nominatim, to separate and validate data.
Request
https://nominatim.openstreetmap.org/search?format=json&limit=1&addressdetails=1&q=1088+Burton+Dr.+REDDING,+CA+96003+US
Response
[
{
"place_id": 266720693,
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_type": "way",
"osm_id": 10591437,
"boundingbox": [
"40.591203388592",
"40.591303388592",
"-122.34939939898",
"-122.34929939898"
],
"lat": "40.59125338859231",
"lon": "-122.34934939898274",
"display_name": "1088, Burton Drive, Lancer Hills Estates, Redding, Shasta County, California, 96003, United States",
"class": "place",
"type": "house",
"importance": 0.621,
"address": {
"house_number": "1088",
"road": "Burton Drive",
"neighbourhood": "Lancer Hills Estates",
"city": "Redding",
"county": "Shasta County",
"state": "California",
"postcode": "96003",
"country": "United States",
"country_code": "us"
}
}
]
And this what I actually want, breaking down of the address string.

How to get 7 day forecast from OpenWeatherMap using JSON Data? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I'm trying to make a Weather application. I know how to fetch the current conditions, but honestly I don't know too much JSON. I have no idea how to fetch the 7-day forecast from OpenWeatherMap. I've tried pretty much everything I can think of, but nothing is working. I'm trying to fetch it from PHP. I really don't get how it works, honestly. If anybody could help, that would be appreciated.
I put ['city']['name']; just as an example.
My PHP code:
<?php
$city="London";
$country="UK";
$url="http://api.openweathermap.org/data/2.5/forecast/daily?q=".$city.",".$country."&units=metric&cnt=7&lang=en&appid=c0c4a4b4047b97ebc5948ac9c48c0559";
$json=file_get_contents($url);
$data=json_decode($json,true);
$data['city']['name'];
?>
Here is the JSON data:
"city":{
"id":2643743,
"name":"London",
"coord":{
"lon":-0.12574,
"lat":51.50853
},
"country":"GB",
"population":0
},
"cod":"200",
"message":0.0132,
"cnt":7,
"list":[
{
"dt":1462532400,
"temp":{
"day":15.49,
"min":13.16,
"max":15.49,
"night":13.16,
"eve":15.49,
"morn":15.49
},
"pressure":1015.77,
"humidity":50,
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03n"
}
],
"speed":4.47,
"deg":116,
"clouds":48
},
{
"dt":1462618800,
"temp":{
"day":23.03,
"min":13.57,
"max":23.03,
"night":15.77,
"eve":21.37,
"morn":13.57
},
"pressure":1015.43,
"humidity":50,
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04d"
}
],
"speed":4.43,
"deg":127,
"clouds":56
},
{
"dt":1462705200,
"temp":{
"day":24.2,
"min":16.14,
"max":24.53,
"night":18.32,
"eve":23.58,
"morn":16.14
},
"pressure":1016.42,
"humidity":42,
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04d"
}
],
"speed":7.22,
"deg":121,
"clouds":68
},
{
"dt":1462791600,
"temp":{
"day":23.4,
"min":17.51,
"max":23.59,
"night":18.36,
"eve":22.42,
"morn":17.51
},
"pressure":1017.75,
"humidity":49,
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"02d"
}
],
"speed":8.36,
"deg":106,
"clouds":8
},
{
"dt":1462878000,
"temp":{
"day":22.79,
"min":16.59,
"max":22.88,
"night":17.15,
"eve":21.54,
"morn":16.59
},
"pressure":1013.95,
"humidity":50,
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}
],
"speed":8.53,
"deg":89,
"clouds":36
},
{
"dt":1462964400,
"temp":{
"day":19.18,
"min":13.92,
"max":19.18,
"night":14.57,
"eve":18.88,
"morn":13.92
},
"pressure":1004.19,
"humidity":0,
"weather":[
{
"id":500,
"main":"Rain",
"description":"light rain",
"icon":"10d"
}
],
"speed":3.24,
"deg":180,
"clouds":22,
"rain":2.13
},
{
"dt":1463050800,
"temp":{
"day":14.84,
"min":8.83,
"max":14.84,
"night":8.83,
"eve":12.92,
"morn":12.53
},
"pressure":1005.56,
"humidity":0,
"weather":[
{
"id":500,
"main":"Rain",
"description":"light rain",
"icon":"10d"
}
],
"speed":4.14,
"deg":325,
"clouds":73,
"rain":2.86
}
]
}
Sorry if this is a really dumb question, but any help would be appreciated, thanks!
So you are actually getting the information for the next 6 days. look at the complete array do an
print_r($data);
As you can see at the complete result theres the 6 days, for example:
[5] => Array
(
[dt] => 1462964400
[temp] => Array
(
[day] => 19.18
[min] => 13.92
[max] => 19.18
[night] => 14.57
[eve] => 18.88
[morn] => 13.92
)
[pressure] => 1004.19
[humidity] => 0
[weather] => Array
(
[0] => Array
(
[id] => 500
[main] => Rain
[description] => light rain
[icon] => 10d
)
)
[speed] => 3.24
[deg] => 180
[clouds] => 22
[rain] => 2.13
)
So what you need to do is a foreach
foreach($data['list'] as $day => $value) {
echo "Max temperature for day " . $day . " will be " . $value[temp][max] . "<br />" ;
}
This will return:
Max temperature for day 0 will be 21.87
Max temperature for day 1 will be 23.03
Max temperature for day 2 will be 24.53
Max temperature for day 3 will be 23.59
Max temperature for day 4 will be 22.88
Max temperature for day 5 will be 19.18
Max temperature for day 6 will be 14.84
Hope this helps!

Create nested json object using php mysql

I have two tables, table 1 has 2 fields (question_pk, question_name) and table 2 has 4 fields(ans_pk, options, question_fk and right_answer). I want to create json like the following structure
{
"type": "quiz",
"name": "Brand Colors",
"description": "Can you identify these brands by the background color?",
"questions": [
{
"name": "Can you identify this color?",
"description": "#ea4c89",
"answers": [
{
"name": "Dribbble",
"description": "dribbble.png",
"weight": 1
},
{
"name": "Amazon",
"description": "amazon.png",
"weight": 0
},
{
"name": "Apple",
"description": "apple.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#3d9ae8",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 0
},
{
"name": "Dropbox",
"description": "dropbox.png",
"weight": 1
},
{
"name": "Wordpress",
"description": "wordpress.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#c4302b",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 1
},
{
"name": "Twitter",
"description": "twitter.png",
"weight": 0
},
{
"name": "Vimeo",
"description": "vimeo.png",
"weight": 0
}
]
}
]
}
MY PHP CODE
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("select * from $questions where sub_cat='$sub_cat_id' order by level_fk asc");
$json_response = array(); //Create an array
$i=1;
while ($row = mysql_fetch_array($result))
{
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("select * from $qus_ans where qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['options'] = $opt_fet['options'];
$row_array['right_ans'] = $opt_fet['right_ans'];
array_push($json_response,$row_array); //push the values in the array
}
$i++;
}
echo json_encode($json_response);
}
?>
And My Result I am getting json response like the following
[
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "45",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "40",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "35",
"right_ans": "1"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "50",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "4 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "1 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "3 times",
"right_ans": "1"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "5 times",
"right_ans": "0"
}
]
In my respose each time the question is repeated so how to avoid and if i want to achive the first json structure, in my PHP code what&where i need to make changes?. If any one knows help me.
Hi try this,
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("SELECT * FROM $questions WHERE sub_cat='$sub_cat_id' ORDER BY level_fk ASC");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$row_array['answers'] = array();
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("SELECT * FROM $qus_ans WHERE qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['answers'][] = array(
'options' => $opt_fet['options'],
'right_ans' => $opt_fet['right_ans'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
}
?>
I think this code is easier to figure out and by the way it uses mysqli ...
This is based on my own data structure, I am in the middle of something and I have no time a.t.m. to adapt it to the question but should easy to figure out how to adapt it to other structures :
$usersList_array =array();
$user_array = array();
$note_array = array();
$fetch_users = mysqli_query($mysqli, "SELECT
ID,
Surname,
Name
FROM tb_Users
WHERE Name LIKE 'G%'
ORDER BY ID") or die(mysqli_error($mysqli));
while ($row_users = mysqli_fetch_assoc($fetch_users)) {
$user_array['id'] = $row_users['ID'];
$user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
$user_array['notes'] = array();
$fetch_notes = mysqli_query($mysqli, "SELECT
id,
dateIns,
type,
content
FROM tb_Notes
WHERE fk_RefTable = 'tb_Users' AND
fk_RefID = ".$row_users['ID'].""
) or die(mysqli_error($mysqli));
while ($row_notes = mysqli_fetch_assoc($fetch_notes)) {
$note_array['id']=$row_notes['id'];
$note_array['dateIns']=$row_notes['dateIns'];
$note_array['type']=$row_notes['type'];
$note_array['content']=$row_notes['content'];
array_push($user_array['notes'],$note_array);
}
array_push($usersList_array,$user_array);
}
$jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);
echo $jsonData;
Resulting JSON :
[
{
"id": "1",
"surnameName": "Xyz Giorgio",
"notes": [
{
"id": "1",
"dateIns": "2016-05-01 03:10:45",
"type": "warning",
"content": "warning test"
},
{
"id": "2",
"dateIns": "2016-05-18 20:51:32",
"type": "error",
"content": "error test"
},
{
"id": "3",
"dateIns": "2016-05-18 20:53:00",
"type": "info",
"content": "info test"
}
]
},
{
"id": "2",
"cognomeNome": "Xyz Georg",
"notes": [
{
"id": "4",
"dateIns": "2016-05-20 14:38:20",
"type": "warning",
"content": "georg warning"
},
{
"id": "5",
"dateIns": "2016-05-20 14:38:20",
"type": "info",
"content": "georg info"
}
]
}
]
A basic class to handle nesting tables into a php array.
PHP CLASS
// chain data into a php array, filtering by relation to parent, based on a structure definition array
// nest child data by relation to parent data
// assign a array label "arr_label" to child definition to define what key the filtered data will use
// assign a parent key "p_key" and a child key "c_key" to child definition to assign connection points from child to parent
// load array data to filter into "arr" key on child definition
class class_chain_filter
{
var $return_arr;
function __construct()
{
} // CONSTRUCTOR
// input a defined filter tree array and output a processed result
function chain_filter($filter_tree)
{
// can feed either a single record a set of rows...
if(!$this->is_assoc($filter_tree['arr']))
$this->return_arr = $filter_tree['arr']; // root for return array
else
$this->return_arr[] = $filter_tree['arr']; // force a numeric array so return is consistent.
$this->do_chain_filter( $filter_tree['next_arrs'], $this->return_arr );
return $this->return_arr;
} // $this->chain_filter($filter_tree) // public
function is_assoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
function do_chain_filter(&$tree_arr, &$final_arr)
{
$cur_final_node = &$final_arr;
if( !is_array($cur_final_node) )
return false;
// send the next_arrs
foreach($final_arr as $f_key => $f_arr)
{
$cur_final_node = &$final_arr[$f_key];
foreach($tree_arr as $n_key => $n_arr)
{
$cur_tree_node = $tree_arr[$n_key];
// $final_cur_el['arr_label'] = 'true';
$next_final_node = &$cur_final_node[$cur_tree_node['arr_label']];
// data up hombre
// filter out array elements not related to parent array
$result = $this->children_of_parent(
$cur_final_node,
$cur_tree_node['arr'],
$cur_tree_node['p_key'],
$cur_tree_node['c_key']
);
$next_final_node = $result;
// now recurse if we have more depths to travel...
if(!empty($cur_tree_node['next_arrs']))
$this->do_chain_filter($cur_tree_node['next_arrs'], $next_final_node);
}
}
} // this->function chain_filter(&$tree_arr, &$final_arr)
// take 2 arrays
// first array is an associative array.
// second array is an array of associative arrays.
// return children of second array that belong to parent array
function children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
{
// parent = a record
// child = multiple records
// filter out children that don't apply to parent.
// return the result
$parent_id = $arr_parent[$key_parent];
foreach($arr_children as $arr_child)
{
$child_id = $arr_child[$key_child];
if($child_id == $parent_id)
$return_arr[] = $arr_child;
}
if(!empty($return_arr))
return $return_arr;
} // this->children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
} // end. class class_chain_filter
LOAD UP SOME TABLES (USE YOUR OWN PREFERRED DB CLASS)
$areas = $db->get("SELECT * FROM areas");
$rooms = $db->get("SELECT * FROM rooms");
$exits = $db->get("SELECT * FROM exits");
DEFINE OUR RETURNED ARRAY TREE STRUCTURE
// predefine tree structure for generation
// structure definition array example...
$tree_arr = array (
"arr" => $areas, // root (can be multiple rows or a single record)
"next_arrs" => array ( // children
0 => array(
"arr" => $rooms, // array to filter against parent
"arr_label" => "rooms", // for the php array label
"p_key" => "id", // field name of parent // eg) id
"c_key" => "areaid", // this array's field name that links it to parent
"next_arrs" => array( // children
0 => array(
"arr" => $exits, // array to filter against parent
"arr_label" => "exits", // for the php array label
"p_key" => "id", // field name of parent / blank if root / eg) id
"c_key" => "roomid" // this array's field name that links it to parent
)
)
)
)
); // $tree_arr
NOW CREATE OBJECT AND PROCESS INTO DESTINATION ARRAY
$c = new class_chain_filter();
$return_arr = $c->chain_filter($tree_arr);
print_r($return_arr);
... AND THE OUTPUT SHOULD LOOK LIKE ...
Array (
[0] => Array
(
[id] => 1
[name] => New World
[author] => anon
[resetfreq] => 3
[rooms] => Array
(
[0] => Array
(
[id] => 1
[areaid] => 1
[name] => Entrance
[description] => The air is humid here.
[exits] => Array
(
[0] => Array
(
[id] => 1
[roomid] => 1
[toroomid] => 2
[direction] => n
[description] => A Hall
[keyid] => 1
)
[1] => Array
(
[id] => 5
[roomid] => 1
[toroomid] => 3
[direction] => s
[description] => Entrance
[keyid] =>
)
)
)
[1] => Array
(
[id] => 2
[areaid] => 1
[name] => A Corridor
[description] => Seems nothing is really going on in this room. Bland tapestry and nothing worth really hanging around for. From the west comes the sound of people training. To the east you can hear people practicing skills and abilities.
[exits] => Array
(
[0] => Array
(
[id] => 2
[roomid] => 2
[toroomid] => 1
[direction] => s
[description] => A Corridor
[keyid] =>
)
[1] => Array
(
[id] => 7
[roomid] => 2
[toroomid] => 4
[direction] => e
[description] => Practice Room
[keyid] =>
)
[2] => Array
(
[id] => 9
[roomid] => 2
[toroomid] => 5
[direction] => w
[description] => Training Room
[keyid] =>
)
[3] => Array
(
[id] => 11
[roomid] => 2
[toroomid] => 8
[direction] => n
[description] => A Bend
[keyid] =>
)
)
)
)
)
)
and then you could just json_encode the array to turn it from a PHP array into a JSON string

How would this PHP array look in Javascript?

I got a little lazy and just used PHP to store all these values, I should be using Javascript to do this though. Whats the best way to do the following in Javascript? I would then be using jQuery's .each function to loop through it.
$accessories = array (
array('name' => 'Chrome pull out wire Basket 500 & 600 wide ', 'price' => '60'),
array('name' => 'Chrome shoe rack 2 Tier', 'price' => '95'),
array('name' => 'Chrome Shoe Rack 3 Tier', 'price' => '145'),
array('name' => 'Chrome pull out trouser rack', 'price' => '40'),
array('name' => 'Pull out tie rack', 'price' => '135'),
array('name' => 'Pull Down hanging Rail 450mm to 1190mm width', 'price' => '33.50'),
array('name' => 'Corner Hanging Rail', 'price' => '33.50')
);
JavaScript doesn't have associative arrays, so you'd have to build it as a series of objects in an array.
var accessories = [
{ 'name' : 'Chrome pull out...', 'price' : 60 },
{ 'name' : 'Chrome shoe rack..', 'price' : 95 }
];
You could then cycle over it using $.each as you requested:
$.each( accessories, function(){
alert( this.name );
});
Fiddle: http://jsfiddle.net/jonathansampson/HXwMc/
Quickly Convert PHP Array to JSON
You can get the above structure easily by passing the array through json_encode():
echo json_encode( $accessories );
It would probably look like this:
var array = [
{"name": "Chrome pull out wire Basket 500 & 600 wide ", "price": "60"},
{"name": "Chrome shoe rack 2 Tier", "price": "95"},
{"name": "Chrome Shoe Rack 3 Tier", "price": "145"},
{"name": "Chrome pull out trouser rack", "price": "40"},
{"name": "Pull out tie rack", "price": "135"},
{"name": "Pull Down hanging Rail 450mm to 1190mm width", "price": "33.50"},
{"name": "Corner Hanging Rail", "price": "33.50"}
];
Note that this is an array of objects. JavaScript doesn't have associative arrays, those are objects.
As Jonathan noted, that's an array of objects in Javascript. It would look like this
var accessories = [
{
name: 'hello',
price: 1.00,
},
{
name: 'world',
price: 2.50,
}
]

Categories