Comparing arrays within a loop

For anyone else, or for someone to maybe give a better, neater, more professional answer, this is what I have ended up doing:

First I added a function to compare the new search data ($newSearch):

function identical_values( $arrayA , $arrayB ) { 
   sort( $arrayA ); 
   sort( $arrayB ); 
 return $arrayA == $arrayB; 
}

Kept the same method for grabbing the variables from URL:

        $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
        $query_str = parse_url($url, PHP_URL_QUERY);
        parse_str($query_str, $query_params);
        $query_params[contract_type] = $term_id;
        $query_params[url] =$url;

Then added the code to run through all saved searches stored in the database:

         $newSearch = (array) $query_params; 
         $sql = " SELECT * FROM  `wp_usermeta` WHERE  `meta_key` =  '_saved_searches' AND  `user_id` =  $user_id ORDER BY `umeta_id` DESC  ";
          $mySavedSearches = $wpdb->get_results( $sql );

             foreach($mySavedSearches as $key=>$value){
               $mySavedSearchesOutput = json_decode($value->meta_value, TRUE);
               $identical = identical_values( $newSearch , $mySavedSearchesOutput );
               if($identical) break;
             }

This part, prevent the double clicking of link if already saved:

       if($identical):
         echo '         <li class="save-search active"></li>';
       else:
         echo '         <li id="save-this-search" class="save-search" data-user-id="'. $user_id.'"><span class="ajax-loader hide"><i class="fa fa-spinner fa-spin"></i></span></li>';
       endif;

Its not pretty, maybe not even safe, but for now works good 🙂

Leave a Comment