Merge 2 Multi-dimensional arrays with some duplicate values - php

I have two arrays that sometimes have matching keys, and I need to merge these values based on the matching fields (make/model/year) and set accordingly based on a value flag each array object has (in this case either fit: B or fit: R)
The first array looks like this and contains fit B's:
$firstArray = [
{ Model: Aston Martin, Make: V12, Year: 2012, fit: B, front_fit: 52, rear_fit: null}
]
Here is the second array and it contains only fit R's:
$secondArray = [
{ Model: Aston Martin, Make: V12, Year: 2012, fit: R, front_fit: null, rear_fit: 24}
]
Notice how most of the values are the same except fit and the front or rear fit based on that flag (B or R). Ideally I would like to merge these two in a new array that would remove the fit and fill out the front_fit and rear_fit fields accordingly:
$mergedNewArray = [
{ Model: Aston Martin, Make: V12, Year: 2012, front_fit: 52, rear_fit: 24}
]
There is a potential third scenario to happen where there may not be a matching model/make/year object in one of the arrays, if this is the case I still want to include the existing record in the new array
so it would turn into something like this:
$mergedNewArray = [
{ Model: Aston Martin, Make: V12, Year: 2012, front_fit: 52, rear_fit: 24},
//This has no matching object to merge with but should still be in this array
{ Model: Dodge, Make: Charger, Year: 2006, front_fit: null, rear_fit: 80}
]
Any help would be much appreciated, The less verbose the better
Edit: Added clarification for the first array and second array containing specific fits

Probably the easiest way to do this is to re-index the first array by the make/model/year, and then iterate over the second array, looking for the same car and if found, updating the record, otherwise creating a new entry in the output. The result array can then be re-indexed numerically using array_values:
$firstArray = json_decode('[
{ "Model": "Aston Martin", "Make": "V12", "Year": 2012, "fit": "B", "front_fit": 52, "rear_fit": null },
{ "Model": "Aston Martin", "Make": "Vantage", "Year": 2017, "fit": "B", "front_fit": 40, "rear_fit": null }
]', true);
$secondArray =json_decode('[
{ "Model": "Aston Martin", "Make": "V12", "Year": 2012, "fit": "R", "front_fit": null, "rear_fit": 24 },
{ "Model": "Dodge", "Make": "Charger", "Year": 2006, "fit": "R", "front_fit": null, "rear_fit": 80 }
]', true);
$result = array();
// index the first array by the model, make and year
foreach ($firstArray as $car) {
unset($car['fit']);
$key = $car['Model'] . '#' . $car['Make'] . '#' . $car['Year'];
$result[$key] = $car;
}
foreach ($secondArray as $car) {
$key = $car['Model'] . '#' . $car['Make'] . '#' . $car['Year'];
// have we seen this car?
if (isset($result[$key])) {
// if so, update
$result[$key]['rear_fit'] = $car['rear_fit'];
}
else {
// create a new entry
unset($car['fit']);
$result[$key] = $car;
}
}
// reindex to numeric keys
$result = array_values($result);
print_r($result);
Output:
Array
(
[0] => Array
(
[Model] => Aston Martin
[Make] => V12
[Year] => 2012
[front_fit] => 52
[rear_fit] => 24
)
[1] => Array
(
[Model] => Aston Martin
[Make] => Vantage
[Year] => 2017
[front_fit] => 40
[rear_fit] =>
)
[2] => Array
(
[Model] => Dodge
[Make] => Charger
[Year] => 2006
[front_fit] =>
[rear_fit] => 80
)
)
Demo on 3v4l.org

Related

laravel - Can I add new items to an array that already has some existing items?

var_export($response) is an array like below:
array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
The below code gives a result like this: "data": 3. I wanted add a new item called points with the $response array, into all elements. But here, it overwrites the existing array. How can I achieve this?
$dat=array_push($response,array('points'=>"3"));
return response()->json(['data' => $dat], 200);
Expected output:
[
{
"courseId": 14,
"tutorName": "admin",
"points": 3
},
{
"courseId": 15,
"tutorName": "merl",
"points": 3
}
]
As mentioned, array_push() returns the new number of elements in the array. That's why you get 3.
You can add your value in all elements of the current response, like this:
foreach ($response as $key => $value) {
$response[$key]['points'] = 3;
}
Then, just return the response :
return response()->json($response, 200);

Iterate through a php multi dimensional array with specific condition

I have a php array below and i want to know how to get number of companies who did a training course. Look below:
Array
(
[0] => Array
(
[date_creation] => Apr 10, 2021 10:17 pm
[idformation] => 84
[idsociete] => 7
[training] => ELECTRICAL SAFETY TRAINING
[company] => ALUCAM
)
[1] => Array
(
[date_creation] => Apr 10, 2021 10:55 pm
[idformation] => 84
[idsociete] => 7
[training] => ELECTRICAL SAFETY TRAINING
[company] => ALUCAM
)
[2] => Array
(
[date_creation] => Apr 12, 2021 03:27 pm
[idformation] => 104
[idsociete] => 201
[training] => FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM
[company] => US EMBASSY
)
);
Each array represents the record of a worker in the database from a company say Alucam and did training Electrical safety.
So from the array above i want to get something like:
2 Alucams did electrical safety as seen in the array.
I just need a clue on how to get the count of persons who did a particular training from the array.
Please help
I assume you can have the same training from different companies, opposite case you can simplified the code.
Input data (I simplified your input array, including only the fields I need):
$workers = array(array("training" => "ELECTRICAL SAFETY TRAINING", "company" => "ALUCAM"),
array("training" => "ELECTRICAL SAFETY TRAINING", "company" => "ALUCAM"),
array("training" => "FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM", "company" => "US EMBASSY"),
array("training" => "FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM", "company" => "ALUCAM")
);
Php code:
$trainingCount = array();
foreach($workers as $worker) {
$training = $worker["training"];
$company = $worker["company"];
if(! array_key_exists($training, $trainingCount)) {
$trainingCount[$training] = array();
}
if(! array_key_exists($company, $trainingCount[$training])) {
$trainingCount[$training][$company] = 0;
}
$trainingCount[$training][$company]++;
}
Result:
array('ELECTRICAL SAFETY TRAINING' => array('ALUCAM' => 2), 'FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM' => array('US EMBASSY' => 1, 'ALUCAM' => 1));
Effectively you have a list of employees with their training listed in a comma separated list?
So basically you need to iterate through the list stripping out the information you require (company & training). Then every time you get a match you increment the matching data.
There are a few ways to do this the simplest would be to iterate through the results to create an array which looks something like...
$countArray = [
"Alucam" => [
"ELECTRICAL SAFETY TRAINING" = 2,
],
];
The code would look like:
$countArray = [];
// Generate the array
foreach ($array as $employee) {
$trainingList = array_map("trim", explode(",", $employee["training"]));
foreach ($trainingList as $training) {
$countArray[$employee["company"]][$training] = ($countArray[$employee["company"]][$training] ?? 0) + 1;
}
}
// Generate the output
foreach ($countArray as $companyName => $training) {
foreach ($training as $trainingName => $trainingCount) {
echo "{$trainingCount} {$companyName} did {$trainingName}", PHP_EOL;
}
}
/*
Output:
2 ALUCAM did ELECTRICAL SAFETY TRAINING
1 US EMBASSY did FORKLIFT
1 US EMBASSY did JLG SCISSOR LIFT
1 US EMBASSY did AERAL PLATFORM
*/
However, this does mean you can have "unusual" characters in array keys which could lead to problems further down the line. So you may do better with a slightly more complicated approach (i.e. having index arrays for the company and training names) which gives an array a little something like...
$countArray = [
'company' => [
0 => 'ALUCAM',
1 => 'US EMBASSY',
],
'training' => [
0 => 'ELECTRICAL SAFETY TRAINING',
1 => 'FORKLIFT',
2 => 'JLG SCISSOR LIFT',
3 => 'AERAL PLATFORM',
],
'count' => [
0 => [
0 => 2,
],
1 => [
1 => 1,
2 => 1,
3 => 1,
],
],
];
The code would look like:
// Generate the array
foreach ($array as $employee) {
if (false === ($companyIndex = array_search($employee["company"], $countArray["company"]))) {
$companyIndex = count($countArray["company"]);
$countArray["company"][] = $employee["company"];
}
$trainingList = array_map("trim", explode(",", $employee["training"]));
foreach ($trainingList as $training) {
if (false === ($trainingIndex = array_search($training, $countArray["training"]))) {
$trainingIndex = count($countArray["training"]);
$countArray["training"][] = $training;
}
$countArray["count"][$companyIndex][$trainingIndex] = ($countArray["count"][$companyIndex][$trainingIndex] ?? 0) + 1;
}
}
// Generate the output
foreach ($countArray["count"] as $companyKey => $companyCount) {
$companyName = $countArray["company"][$companyKey];
foreach ($companyCount as $trainingKey => $trainingCount) {
$trainingName = $countArray["training"][$trainingKey];
echo "{$trainingCount} {$companyName} did {$trainingName}", PHP_EOL;
}
}
You can use array_count_values and array_column to achieve something like this: You can modify as required.
$arr = [
['date_creation' => 'Apr 10, 2021 10:17 pm', 'idformation' => 84, 'idsociete' => 7, 'training' => 'ELECTRICAL SAFETY TRAINING', 'company' => 'ALUCAM'],
['date_creation' => 'Apr 10, 2021 10:17 pm', 'idformation' => 84, 'idsociete' => 7, 'training' => 'ELECTRICAL SAFETY TRAINING', 'company' => 'ALUCAM'],
['date_creation' => 'Apr 12, 2021 03:27 pm', 'idformation' => 104, 'idsociete' => 201, 'training' => 'FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM', 'company' => 'US EMBASSY'],
];
$training = 'ALUCAM';
$companies = array_count_values(array_column($arr, 'company'))[$training]; // outputs: 2

PHP sum array value based on textual duplicate in another array

I have two arrays, both will always be the same count length. One has doubles mixed with integers, the second has textual (string only) values. They do correlate so I need them both to stay in order. Sorry no keys to work with (by design).
I need to sum the values where I have duplicates in the array that has strings.
Example
$dataLabelGraph = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding", "Coding");
So my algorithm should look like this after
$dataLabelGraph = array(21.86, 8, 1, 0.5);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Content");
I was trying to adapt this solution, from the awesome brain of Martin D. # https://stackoverflow.com/a/22071693/12835769
$records_array = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding");
$quantities_array = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$new_array = array();
foreach ($records_array as $record_position => $new_array_key){
$new_array[$new_array_key] += $quantities_array[$record_position];
}
var_dump($new_array);
Gives something like this, which is close but I need them to remain in two separate arrays
array (size=4)
'Coding' => float 21.86
'Web development - Coding' => int 8
'Meeting' => int 1
'Content' => float 0.5
Any help to get me over the line would be immensely helpful. Kudos.
Group by the "name" and sum as you iterate. When the loop is finished, split the keys and the values into separate arrays.
Code: (Demo)
$records = [
"Coding",
"Web development - Coding",
"Meeting",
"Coding",
"Coding",
"Content",
"Coding",
"Coding"
];
$quantities = [
3,
8,
1,
4.85,
1,
0.5,
6.01,
7
];
$result = [];
foreach ($records as $index => $label){
$result[$label] = ($result[$label] ?? 0) + $quantities[$index];
}
var_export(array_keys($result));
var_export(array_values($result));
Outputs:
array (
0 => 'Coding',
1 => 'Web development - Coding',
2 => 'Meeting',
3 => 'Content',
)
array (
0 => 21.86,
1 => 8,
2 => 1,
3 => 0.5,
)

Need help parsing JSON output

I'm making a REST call in PHP and returning JSON. I'm eventually putting this into tables, but trying to output the value for now to get the hang of it.
There are values in the "data" field I would like to get into variables. In my example they would be "201807", 23.43 and "201806", 22.54. It's the first two values of the property "data"
My code looks like this:
<?php
$service_url = "http://api.eia.gov/geoset/?geoset_id=ELEC.PRICE.RES.M&regions=USA-AL,USA-AK,USA-AR&api_key=3a8b92cfaf3a21e2e990f228c9152eeb&out=json&start=2018";
$get_data = callAPI('GET', $service_url, false);
$response = json_decode($get_data);
foreach ($response as $r) {
echo $row->name;
echo $row->geoset_id;
}
?>
And JSON looks like this:
{
"geoset": {
"geoset_id": "ELEC.PRICE.RES.M",
"setname": "Average retail price of electricity : residential : monthly",
"f": "M",
"units": "cents per kilowatthour",
"unitsshort": null,
"series": {
"USA-AK": {
"series_id": "ELEC.PRICE.AK-RES.M",
"name": "Average retail price of electricity : Alaska : residential : monthly",
"region": "USA-AK",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 23.43],
["201806", 22.54],
["201805", 22.16],
["201804", 21.61],
["201803", 21.47],
["201802", 21.11],
["201801", 21.67]
]
},
"USA-AL": {
"series_id": "ELEC.PRICE.AL-RES.M",
"name": "Average retail price of electricity : Alabama : residential : monthly",
"region": "USA-AL",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 12.28],
["201806", 12.41],
["201805", 12.49],
["201804", 12.79],
["201803", 12.65],
["201802", 12.29],
["201801", 11.59]
]
},
"USA-AR": {
"series_id": "ELEC.PRICE.AR-RES.M",
"name": "Average retail price of electricity : Arkansas : residential : monthly",
"region": "USA-AR",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 9.98],
["201806", 9.99],
["201805", 9.89],
["201804", 10],
["201803", 10.47],
["201802", 9.8],
["201801", 9.36]
]
}
}
}
}
So far I'm getting NULL values back.
As you have used json_decode your result will be convert to object type. so you should do as follows:
$geoset = $response->geoset;
$geosetid = $geoset->geoset_id;
foreach ($geoset->series as $row) {
echo $row->name;
$data = $row->data; //this will produce the values as array
}
Your data array will be like this:
Array
(
[0] => Array
(
[0] => 201807
[1] => 23.43
)
[1] => Array
(
[0] => 201806
[1] => 22.54
)
)
...
Hopefully this helps! :)
Your code will never work, because:
You iterate $response as $r, but use $row inside;
The $response has only one child: geoset. There is no $response->name neither $response->geoset_id.
If you want the geoset_id, you must access using: $response->geoset->geoset_id.
To achieve this:
There are values in the "data" field I would like to get into variables
Use the following code:
foreach ($response->geoset->series as $series) {
foreach ($series->data as $data) {
$date = $data[0];
$value = $data[1];
}
}

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

Categories