Solved

PHP compare keys and values in two arrays

Posted on 2004-08-20
17
764 Views
Last Modified: 2012-05-05
Hello Experts !

I need to compare indexes and values in two arrays !

My arrays are:
accommodation_start
accommodation end

the values in them come from a mysql database, the keys have a hotel_id in them and the values have a hotel_season_id in them

at the moment i need to check where the first arrays key (hotel_id) matches the second arrays index (hotel_id) and when they do match, I need to check whether the values of the indexes are the same,

At this stage:
 if the values of the indexes match, the script does something
if not, I just want to say that the values dont match !

Will post for more help if I get suck with the script after this !
0
Comment
Question by:Delacourt
  • 8
  • 3
  • 2
  • +3
17 Comments
 
LVL 26

Expert Comment

by:ushastry
ID: 11851006
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11851173
thanks for this, but i need to compare, not check differences !
I have tried using the array_key_diff() function, but its not giving me what i want ! because i need to match values, where the index is the same !

please see: http://www.experts-exchange.com/Web/Web_Languages/PHP/PHP_Databases/Q_21098019.html

to see if I am doing the right thing !
0
 
LVL 48

Expert Comment

by:hernst42
ID: 11851417
maybe the following works

$different= false;
foreach ($accommodation_start as $k1 => $v1) {
    if (!array_key_exists($k1, $accommodation_end)) {
        // Key of array one does not exits in the second array
        $different = true;
        break;
    } else {
        if ($accommodation_end[$k1] != $v1) {
            // The values are different
            $different = true;
            break;
        }
    }
}
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11858329
Thanks Hernst24,

Problem is, I need to do the following: While your code above does work, it is not what I am looking for !

First, I need to check that the keys are the same in the arrays, if not then stop code.
If keys are the same, I need to compare values of those keys.
 - If not the same then there is still more code to be written, so can be stopped here.
 - If the values are the same, then I need to carry on with the code

Herewith are may arrays

// in which season does the client want the accomodation to start?
$sql1 = "select * from hotel_season_table
where hotel_season_start_date<'" . $arrival_date . "' and
hotel_season_end_date>'" . $arrival_date . "'";
$query1 = mysql_query( $sql1 );
while( $result1 = mysql_fetch_array( $query1 ) ){
  // populate an array with list of hotels
  $accommodation_start[ $result1[ 'hotel_id' ] ] = $result1[ 'hotel_season_id' ];
}

// in which season does the client want the accomodation to end?
$sql2 = "select * from hotel_season_table
where hotel_season_start_date<'" . $departure_date . "' and
hotel_season_end_date>'" . $departure_date . "'";
$query2 = mysql_query( $sql2 );
while( $result2 = mysql_fetch_array( $query2 ) ){
  // populate an array with list of hotels
  $accommodation_end[ $result2[ 'hotel_id' ] ] = $result2[ 'hotel_season_id' ];
}

So I now have two arrays,
$accommodation_start
$accommodation_end
I need to check that the indexes (hotel_id) match, so that I can see if the $arrival_date and $departure_date fit into the same season of the hotel (hotel_season_id),

then I can go on to get the rates if the seasons area the same, if not the same I need to break the dates up, but Ill post another question on that if I get stuck after I get this working !!!

Thanks in advance !
0
 
LVL 2

Expert Comment

by:blackelvis
ID: 11861837
a little modification of hernst42's script, i think this is basically what you are looking for:

foreach ($accommodation_start as $k1 => $v1) {
    if (!array_key_exists($k1, $accommodation_end)) {
        // Key of array one does not exits in the second array
        // some function call for this case
    } else {
        if ($accommodation_end[$k1] != $v1) {
            // The values are different
            // some function call for this case
        }else {
            // the values are the same
            // some function call for this case
        }
    }
}
0
 
LVL 2

Expert Comment

by:blackelvis
ID: 11861845
or do you have to check that all array keys are the same the very first before doing anything else?
0
 
LVL 48

Expert Comment

by:hernst42
ID: 11863089
If all keys for both arrays must be the same try this:

$different= false;
if (count($accommodation_start) == count($accommodation_end) && count(array_diff(array_keys($accommodation_end), array_keys($accommodation_start))) == 0) {
    foreach ($accommodation_start as $k1 => $v1) {
        if (!array_key_exists($k1, $accommodation_end)) {
            // Key of array one does not exits in the second array
            $different = true;
            break;
        } else {
            if ($accommodation_end[$k1] != $v1) {
                // The values are different
                $different = true;
                break;
            }
        }
    }
} else {
    //The keys of the arrays are different
    $different = true;
}
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11863139
Thanks Experts for all your help above !

To answer your qestions, BlackElvis and Hernst24: If and when the keys are the same, I want to see if the values are the same !

i.e.

a client fills a form with arrival and departure dates, php page processes these dates as above when they were put into two arrays !

Now, I need to check that the hotel_id as index in the first array, is also the hotel_id in the second array, (rates are from room in a hotel - but wont work right if it is two different hotels !) So, once I have the indexes being the same, I need to check whether the hotel_season_id is the same (value / v1) if it is this means that the datesa fall into a season and I can go ahead and get the rates per night for this, if the hotel_id is the same but the values are not, then we know the dates overlap in between two seasons (i.e. low and high season) and the rates will be different per day !

Thanks again, I am going to be checking and playing around with the code now !
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:Delacourt
ID: 11864965
maybe my table structure would help, then you could see where i am getting my results of the queries from :

hotel_season_table
-----------------------
hotel_season_id (PK)
hotel_id (FK)
hotel_season_name
hotel_season_start_date
hotel_season_end_date
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11864968
room_rate_table
--------------------
room_rate_id (PK)
hotel_season_id (FK)
room_id (FK)
room_rate_name
room_rate_amount

0
 
LVL 3

Expert Comment

by:odders
ID: 11867079
im not sure if this is what your getting at, but here goes:

if(array_keys(accommodation_start) == array_values(accommodation_end)){
  echo("tis good");}
else{
  echo("tis bad");}

what this does is check all of the keys in one array agaist all of the values in another. Because the pulled keys and values both turn out as values in the generated arrays, they will have the same indexes and data if all is good.

Hope that is what you were after...
0
 
LVL 2

Expert Comment

by:blackelvis
ID: 11868231
if(array_keys(accommodation_start) == array_values(accommodation_end))

this doesn't work because it will always return true. array_keys() and array_values() return arrays.

do you want to calculate the money one has to spend for a room with different rates per day (because of different seasons)? so you would only need the data of one hotel and one room? or can the customer enter different hotels, rooms and so on in one and same html form? i'm still not very clear about what the task is. maybe you could explain this whole thing from the customers point of view and not trying to explain your partial abstract way of soluting it, because i don't have your background.
0
 
LVL 3

Expert Comment

by:odders
ID: 11876472
fair enough. i havnt tried it, and wasnt sure if the comparison would would compare the arrays exactly or just check each if it returned true. you could just stick it in a while and increment each array and check each item against the next.

yeah, im still confused about what exactly delacourt is after. just thought id have a go...
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11879350
ahoy me m8s

to clarify from customer on web side, in expectation of getting two things back on different occasions:
1: a list of hotels and their rates for the dates given in the form
2: rates for the rooms in a specific hotel
 FORM
the client adds $arrival_date and $departure_date to a form and presses submit, either for a list of hotels in a city / on a hotels own page

the arrays are made as follows: (compliments of gicutza-cj)

// in which season does the client want the accomodation to start?
$sql1 = "select * from hotel_season_table
where hotel_season_start_date<'" . $arrival_date . "' and
hotel_season_end_date>'" . $arrival_date . "'";
$query1 = mysql_query( $sql1 );
while( $result1 = mysql_fetch_array( $query1 ) ){
  // populate an array with list of hotels
  $accommodation_start[ $result1[ 'hotel_id' ] ] = $result1[ 'hotel_season_id' ];
  // ^^^ we assure for unicity; not writing an identifier more than once in our array
}

// in which season does the client want the accomodation to end?
$sql2 = "select * from hotel_season_table
where hotel_season_start_date<'" . $departure_date . "' and
hotel_season_end_date>'" . $departure_date . "'";
$query2 = mysql_query( $sql2 );
while( $result2 = mysql_fetch_array( $query2 ) ){
  // populate an array with list of hotels
  $accommodation_end[ $result2[ 'hotel_id' ] ] = $result2[ 'hotel_season_id' ];
  // ^^^ we assure for unicity; not writing an identifier more than once in our array
}

**************THIS IS WHERE I NEED TO COMPARE**************
**************DOES NOT HAVE TO FOLLOW BELOW CAN BE A DIFFERENT WAY**************
foreach( $accommodation_start as $index => $value){
// traverse the first array: $accomodation_start[] // <<<<<<< having trouble getting this right
  // compare: see if this index is in the second array // <<<<<<< having trouble getting this right
  // if it is, compare the ids of the seasons; // <<<<<<< having trouble getting this right
  // if different seasons, then divide this into 2 periods: $arrival_date -> $1st_season_end_date, // <<<<<<< having trouble getting this right
  // $1st_season_end_date -> $departure_date; each of these 2 has a corresponding [hotel_season_id], // <<<<<<< having trouble getting this right
  // the first is from the first array, the second ... from the second array
  // populate an array $possibilities like this: - index the array by the hotel_id
  // - search for the hotel_season_id in the [rooms_table] and compute the amount for the period
  // - if previously splitted into 2 sub-periods, sum up the amounts and insert the total value in the array
}
// traverse and display the array $possibilities; use different queries inside this loop if more informations are
// needed (city, a.s.o)

0
 
LVL 1

Author Comment

by:Delacourt
ID: 11885057
point increase, pursuing other avenues soon
0
 
LVL 2

Accepted Solution

by:
Rajkumar_G earned 500 total points
ID: 11912138
<?
  $start=Array(1=>24,2=>34,45=>231,5=>30);
  $end=Array(2=>39,3=>120,6=>458,4=>987,1=>24,5=>30);


   $arr1=array_keys ($start);   //to get all the keys of start array
   $arr2=array_keys($end);    //to get all the keys of end array
   echo "<br>Keys of Start array : ";
   echo "<pre>";
     print_r($arr1);
   echo "</pre>";
   echo "<br>Keys of End Array  :  ";
   echo "<pre>";
   print_r($arr2);
   echo "</pre>";

   echo "<br>Intersection of keys of the two arrays  :   ---- Result array ";
   $result=array_intersect($arr1,$arr2);   //    to get the identical keys from both the arrays
   echo "<pre>";
     print_r($result);
   echo "</pre>";

  //to find the corresponding values for the identical keys
   for($i=0;$i<=count($result);$i++)
     {
       $res_value[]=$start[$result[$i]];
       $res_value[]=$end[$result[$i]];
     }
   echo "<pre>";
     print_r($res_value);
   echo "</pre>";

   //to get identical values from the array
   for($i=0;$i<=count($res_value);$i++)
    {
     for($j=$i+1;$j<=count($res_value);$j++)
      {
        if($res_value[$i]==$res_value[$j])
          {
             $res_final_val[]=$res_value[$i];
          }
      }
    }
   echo "<br>Final identical values from 2 arrays:";
  echo "<pre>";
     print_r($res_final_val);
   echo "</pre>";


  //to get keys for the identical values from the array
    for($i=0;$i<=count($res_final_val);$i++)
      {
        $res_final_key[]=array_search($res_final_val[$i],$start);
      }

   echo "<br>Final identical keys from 2 arrays:";
  echo "<pre>";
     print_r($res_final_key);
   echo "</pre>";

?>

I think this is the required code.I have done it with an example. Customise it as per your requirements.As you want to insert code in the middle for true and false returns the code runs to lines. otherwise you can use array_intersect_assoc() function to get the identical vale with key if you don;t want to insert code in the middle.
0
 
LVL 1

Author Comment

by:Delacourt
ID: 11912612
Rajkumar_G

Thanks for your input on this code, I am using it now and it seems to be working perfectly, except for:

Final identical values from 2 arrays
&
Final identical values from 2 arrays

Basically, I need to do the following: see question: http://www.experts-exchange.com/Web/Web_Languages/PHP/PHP_Databases/Q_21098019.html
How would I go about doing this, and is the above solution the correct way to do this : will post another question before you answer if you wish !
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now