Hello all,

I have a multidimentional array

$array_name[value?][]
$array_name[value?][]
$array_name[value?][].... etc

which I would like to compare using the array_intersect comand.

in long hand would look like
$result = array_intersect($array_name[value?],$array_name[value2],....etc);

Is there a realy neat way of passing these changing number of arrays to a function.

I hope I made sense, and if I have asked an old question I have looked honest !!

Thank you in advance

Thomas Ashbee

    If I understand you correctly, this is probably what you want.

    <?PHP
    $a = array(array(1, 2, 3, 4, 5, 6, 7, 8, 9),
    array(1, 2, 3, 4, 5,),
    array(1, 3, 4, 5, 7),
    array(1, 4, 5));

    $intersect = array_map("cumulative_intersect", $a);
    print_r(cumulative_intersect());
    
    function cumulative_intersect($in = null) {
    	static $accumulator = array();
    	if (is_null($in)) {
    		return($accumulator);
    	}
    	if (sizeof($accumulator) == 0) {
    		$accumulator = $in;
    	}
    	$accumulator = array_intersect($accumulator, $in);
    	return($accumulator);
    }

    ?>

    Returns:

    Array
    (
    [0] => 1
    [3] => 4
    [4] => 5
    )

      Slight correction, that code would mess up your original array. This is fixed:

      <?PHP
      $a = array(array(1, 2, 3, 4, 5, 6, 7, 8, 9),
      array(1, 2, 3, 4, 5,),
      array(1, 3, 4, 5, 7),
      array(1, 4, 5));

      $intersect = array_map("cumulative_intersect", $a);
      print_r(cumulative_intersect());
      
      function cumulative_intersect($in = null) {
      	static $accumulator = array();
      	if (is_null($in)) {
      		return($accumulator);
      	}
      	if (sizeof($accumulator) == 0) {
      		$accumulator = $in;
      	}
      	$accumulator = array_intersect($accumulator, $in);
      }

      ?>

        Sorry that function was kind of off-the-cuff. It doesn't properly handle when there are no results after an intersect. This fixes it and every other situation I could think of. 🙂

        <?PHP
        $a = array(array(1, 2, 3, 4, 5, 6, 7, 8, 9),
        array(1, 2, 3, 4, 5,),
        array(1, 3, 4, 5, 7),
        array(1, 4, 5));

        $intersect = array_map("cumulative_intersect", $a);
        print_r(cumulative_intersect());
        
        function cumulative_intersect($in = null) {
        	static $accumulator = null;
        	if (is_null($in)) {
        		return($accumulator);
        	}
        	if (is_null($accumulator)) {
        		$accumulator = $in;
        	}
        	$accumulator = array_intersect($accumulator, $in);
        }

        ?>

          Majik

          Thank you so much for taking the time to answer, my delay is due to the fact it gave me loads to do (and I had to upgrade my php).

          It's all working, and your help will be at the core of a Taxi routing routine.

          Thanks again

          Thomas Ashbee

            Write a Reply...