Link to home
Start Free TrialLog in
Avatar of Delacourt
DelacourtFlag for South Africa

asked on

PHP compare keys and values in two arrays

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 !
Avatar of Umesh
Umesh
Flag of India image

Avatar of Delacourt

ASKER

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: https://www.experts-exchange.com/questions/21098019/Hotel-Bookings-Reservations-Rooms-with-rates-according-to-seasonal-dates.html

to see if I am doing the right thing !
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;
        }
    }
}
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 !
Avatar of blackelvis
blackelvis

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
        }
    }
}
or do you have to check that all array keys are the same the very first before doing anything else?
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;
}
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 !
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
room_rate_table
--------------------
room_rate_id (PK)
hotel_season_id (FK)
room_id (FK)
room_rate_name
room_rate_amount

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...
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.
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...
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)

point increase, pursuing other avenues soon
ASKER CERTIFIED SOLUTION
Avatar of Rajkumar_G
Rajkumar_G

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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: https://www.experts-exchange.com/questions/21098019/Hotel-Bookings-Reservations-Rooms-with-rates-according-to-seasonal-dates.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 !