associating two separate arrays for itinerary system - php

I am trying to build a travel itinerary system. The user selects the dates of travel, and then may add items to each day.
I have an array of dates, stored in a session in the format:
array(
(int) 0 => '2012-08-25',
(int) 1 => '2012-08-26',
(int) 2 => '2012-08-27'
)
They will then choose attractions, which I wish to store in an array in the format:
array(
(int) 0 => array(
'Attraction' => array(
'attraction_id' =>'1',
'name' => 'Place One',
)
),
(int) 1 => array(
'Attraction' => array(
'attraction_id' => '2',
'name' => 'Place Two',
)
),
I'd like to be able to output:
2012-08-25
Place One
Place Two
2012-08-26
nothing here yet!
2012-08-27
nothing here yet!
So, each item of the first array contains an array of items, if that makes sense. I am struggling with the logic of associating the keys of the days array with the items array.
I looked at array_merge but that doesn't seem to do what I need.
Is there an easy way to achieve this?

This code does exactly what you ask. Unfortunately, I fear your question doesn't reflect your aim given the example. Using keys to link data will led to 1-1 relationship, where as you seem to need a 1-n. You should have a foreign key field in the attraction array, like date_id.
$array= array();
foreach($dates as $date_key=>$date){
$array[$date]=array();
foreach($attractions as $attraction_key=>$attraction){
if($date_key==$attraction_key){
$array[$date][]=$attraction['Attraction']['name'];
}
}
}

Related

Simpliest way to build a multi-dimensional array with SQL result?

I am currently building a web planning and I want to show some data in the period display.
I have a PHP file where I create my SQL request over ~13 tables and fetch all results (I use PDO::FETCH_ASSOC), then I have to loop over my result to build the array I want.
The problem is I need to build a complicated array with lot of data. Here is the kind of result I want to achieve :
$result = array(
$place_1 => array(
'data_place' => array(
'id' => ...,
'name' => ...,
// etc.
),
'data_target' => array(
$target_type_1 => array(
$name_1 => ...,
$name_2 => ...,
// etc.
),
$target_type_2 => array ( ... ),
// etc.
),
'data_isOpen' => array(
$day_1 => array(
$hour_begin => ...,
$hour_end => ...
),
$day_2 => array ( ... ),
// etc.
),
'data_box' => array(
// same kind of stuff with more dimension
)
),
...
$place_n = array(
// same
)
);
When I execute my request, I get something like 3000 array with all the data I need, but I only have 29 places in database so there is a lot of repetition...
$result = array(
0 => array(
"id" => ...,
"name" => ...,
// the list of all fields I need in my big array
),
...
n => array(
// same
)
);
I almost manage to achieve the result I want with some "foreach" and headaches but here is my question :
Is it possible to build a SQL request and fetch the result as I want? I mean, can I group all the result by "id_place" for example but wihtout lost information? And if it's possible, can we do it multiple time?
The idea is to get a result with one array for every place (so 29 and not 3000), then for every "place array", group for example the "hour_begin" and "hour_end" by "opening_day", etc...
Sorry if it's a duplicate, I didn't saw any positive anwser to my question so I try again !

Inserting Array into PHP Array

Working with an array file with following structure. I know there are additional arrays that need to be inserted under each array 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
Once this array is created, I am using a list to loop thru to verify that each value in the list is placed in each 'color' array as follows
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
For simplicity my controllist looks like
Gone With The wind
Across The Great Divide
Goldfinger
Once complete I should end up with the info for Across The Great Divide inserted into 'color'=> 'category a' as the [2] with Goldfinger moving down one. In 'color'=>category_b' the first array should be Gone With The Wind. Any of the 'color' arrays could be missing an array at any position. To sum it up, need to check for the existence of a value from the list, if not present insert into the array. Other than using the foreach loops shown is there an easier way of doing this? If not how can I get the information inserted into the proper position?
Thanks
EDIT:
I believe the question may not be clear. What I need to do is check for the existence of one array in another. If the value in conrollist is not present in the array, insert an array into the array according the position in the conrollist. The inserted array will have the same structure as the others (I can take care of this part). I am having trouble determining if it exist and if not inserting it. Hope this helps
You might want to be using a for loop instead so you have a pointer on each iteration in order to determine where you are in the array.
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}

CakePHP 2.4.4 How can I sort a multi-dimensional array with Hash::sort by string keys and values?

I don't understand the docs regarding the Hash 'path', so I've had no luck. I'm trying to sort each layer alphabetically:
array(
'music' => array(
'genre' => array(
(int) 0 => 'Dubstep',
(int) 1 => 'Blues',
(int) 2 => 'Classical'
),
'instrument' => array(
(int) 0 => 'Guitar (Electric)',
(int) 1 => 'Bassoon',
(int) 2 => 'Harmonica (Diatonic)'
),
'anotherLot' => array(
I need to sort the first later of arrays by key, then the second later in each by key, and the third by the values, so I imagine the two deeper layers would be done with a nested foreach.
I'm not familiar with CakePHP's Hash class, but here is a plain PHP solution:
ksort($data); // sort main array by keys
foreach ($data as &$outer)
{
ksort($outer); // sort next layer by keys
foreach($outer as &$inner)
{
asort($inner); // sort inner arrays by values
}
}

Accessing multi-dimensional, unordered, associative arrays in an ordered fashion using an incremental loop

This is primarily a PHP answer, but the methodology may in fact be language agnostic.
After running a CSV file through a simple parser, I was given a multidimensional array that resembled something akin to this:
array( 'estimated' =>
array(
array( "TITLE" => 'MAIN', "CURR_PERF" => 100, "POT_PERF" => 75 ),
array( "TITLE" => 'HEAT', "CURR_PERF" => 90, "POT_PERF" => 60 ),
array( "TITLE" => 'CO2', "CURR_PERF" => 56, "POT_PERF" => 40 ),
),
'actual' =>
array(
array( "TITLE" => 'MAIN', "CURR_PERF" => 100, "POT_PERF" => 75 ),
array( "TITLE" => 'HEAT', "CURR_PERF" => 89 , "POT_PERF" => 75),
array( "TITLE" => 'CO2', "CURR_PERF" => 40, "POT_PERF" => 20 ),
);
);
Now, horrific data structure to one side, without refactoring of the underlying parser - how would be the best way to ensure that you can access these in a specific order? Without necessarily touching the underlying parser?
If you loop through using a for()/foreach() loop you're only going to be able to read them in a linear order - increasing or decreasing down the elements. You're not necessarily going to be able to drill down and get the specific value required.
For instance, the CSV file could express the values for estimated in a different order to the values for actual; and it may be required that they are output in yet another order.
For example, here are three different orders off the top of my head:
-> MAIN HEAT CO2
-> HEAT MAIN CO2
-> CO2 HEAT MAIN
Furthermore, as is quite usual, the label names in the CSV file are not exactly user-friendly - so they need to be 'translated' (if you like) in to something more human-friendly. Naturally, without the use of lots of if() statements if preferable!
Given it's a very specific use case, but it's something I've seen before with regards to arrays being serialised - and often finding out that they are actually nested.
I've posted one possible solution, but would be happy to see others. (In the past when I've done similar I've never accepted my own answer ;)) I'm sure there must be a more elegant way than the one I've devised..!
This was the quickest (and neatest) solution I could come up with on the spot at the time, but it's not one that I take very much pride in..! It involves multiple loops, the use of several arrays and seems to be an over-engineered mechanism for doing something which should surely be pretty simplistic?
First of all I've created an associative array to use as a dictionary to look up translations for text strings found in the CSV file:
$tbl = array( "MAIN"=>"Main Costs",
"TOTAL"=>"Total Costs",
"CO2"=>"Gas expended" );
Next up, I created an array to use as an 'index' - I entered the key values here in the order I would like them to be accessed in the application:
$index = array( "MAIN", "TOTAL", "CO2" );
I then created two blank arrays and populated them with the data from the child arrays, by using a loop I was able to make them associative - allowing me to specify use the TITLE fields as keys:
$estimated = array();
$actual = array();
foreach( $bills['estimated'] as $bill ){
$estimated[ $bill['title'] ] = $bill;
}
foreach( $bills['actual'] as $bill ){
$actual[ $bill['title'] ] = $bill;
}
By doing this I could loop through them in a specific order, regardless of the order they were parsed in, like so:
for($i=0; $i<3; $i++){
$bill = $estimated[ $index[ $i ] ];
printf(" %s: %d ", $tbl[ $index[ $i ] ], $bill['CURR_PERF'] );
}
Which would output the following, in the order I specified:
// 1. Main Costs: 100
// 2. Total Costs: 90
// 3. Gas Expended: 56
Naturally, this order could easily be changed if required. It does however:
require using an array specifically to act as an index
require using two loops simply to initialise
uses a total of four extra arrays
If this array was assigned to variable $ary like:
$ary = array(
'estimated' =>
array(
array('TITLE' => 'MAIN', 'CURR_PERF' => 100, 'POT_PERF' => 75),
array('TITLE' => 'HEAT', 'CURR_PERF' => 90, 'POT_PERF' => 60),
array('TITLE' => 'CO2', 'CURR_PERF' => 56, 'POT_PERF' => 40),
),
'actual' =>
array(
array('TITLE' => 'MAIN', 'CURR_PERF' => 100, 'POT_PERF' => 75),
array( 'TITLE' => 'HEAT', 'CURR_PERF' => 89 , 'POT_PERF' => 75),
array( 'TITLE' => 'CO2', 'CURR_PERF' => 40, 'POT_PERF' => 20 ),
);
);
Your estimated array could be accessed like:
$newVar = $ary['estimated'][2]['CURR_PERF'];
$newVar would be 56. You can reassign a value as well, like:
$ary['estimated'][0]['POT_PERF'] = 300;
That first array in the estimated array used to be 75 and is now 300.
This is how you get and set specific values in a Multi-dimensional Array.
To sort the arrays, if you need to loop over and maintain their indexes, see PHP's uasort() function. This may take some work, on your part, to develop a cmp_function, but should do what you're looking for in a different way.
See,
http://www.php.net/manual/en/function.uasort.php
and
http://www.php.net/manual/en/function.usort.php ,
which explains cmp_function better.

PHP multi-dimentional array sort

I have an array that I would like to sort, that should be easy, except that I build my array in a strange manners (for different reasons) that make it hard to sort. Here is my array :
$arrayCEO =array(
'companyName' => array(0=>'name1', 1=>'name2'),
'link' => array (0=>'link1', 1=>'link2'),
'isin' => array (0=>'isin1', 1=>'isin2'),
'mktCap' => array (0=>'mktCap1', 1=>'mktCap2'),
'nbShares' => array (0=>'nbShares1', 1=>'nbShares2'),
'amount' => array (0=>'10', 1=>'20'));
Is that possible to sort by "amount" without breaking the order in the others arrays?
Do you recommend me to rewrite my code to build an array like this one :
$arrayCEO =array(
0 => array ('name' => 'name1', 'link' => 'link1', 'isin' => 'isin1', …),
1 => array ('name' => 'name2', 'link' => 'link2', 'isin' => 'isin2', …));
2 => ...
I know this one would be simple to sort but it's a lot of work to rewrite my piece of code.
Thanks,
Dorian
It makes a lot more sense to rewrite your arrays to store in the more conventional format you described - (It's always better to organise things in decreasing magnitude 'Root > rows > fields' instead of 'Root > fields > rows')
If you didn't want to change you could probably use the usort function and roll your own sorting method, but it might be a bit of work to make it play nicely.

Categories