-1

I want to find values in multidimensional array. I have an array like this:

array(4) { 
    [0]=> array(2) { 
        [0]=> string(3) "840" 
        [1]=> string(3) "841" } 
    [1]=> array(1) { 
        [0]=> string(3) "842" } 
    [2]=> array(4) { 
        [0]=> string(3) "333" 
        [1]=> string(3) "723" 
        [2]=> string(3) "749" 
        [3]=> string(3) "750" } 
    [3]=> array(4) { 
        [0]=> string(3) "248" 
        [1]=> string(3) "268" 
        [2]=> string(3) "269" 
        [3]=> string(3) "270"   } 
}

I have found here this function:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

But this if statement:

if(!$this->in_array_r($id, $myArray) {} 

doesn't search... I really don't know why. What I am doing wrong guys? I have analised my code multiple times and it seems to be ok.

EDIT: I have this:

foreach($koszyk as $Id_produkty => $Ilosc) {
   if(!$this->in_array_r($Id_produkty, $myArray)) {
       // If the Id_produkty variable is not in $myArray I want to skip to the next element in $koszyk
       continue;
   }

   // Here is mySql query and I'm retrieving data depends on $Id_produkty
}

But it seems like the in_array_r function exits the code after it... It doesn't return any value for me.

Wow, when I set error_reporting to E_ALL I got this error: Call to undefined function in_array_r() I have to figure it out why is that

EDIT2: Ok I got this, I had to add $this-> before calling in_array_r function inside.

Community
  • 1
  • 1
XardasLord
  • 1,706
  • 2
  • 18
  • 37
  • 4
    It always helps if we know what the output is what you are expecting, and the output you are actually getting.. Edit: Please add to question, not in a comment. – Naruto Sep 29 '15 at 13:16
  • 1
    please provide more details. – Ninju Sep 29 '15 at 13:17

2 Answers2

0

Are you asking for an in_array() function in an multidimensional array? If so then this code might be what you are asking, your question is not clear though.

function in_multiarray($elem, $array)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom] == $elem)
            return true;
        else 
            if(is_array($array[$bottom]))
                if(in_multiarray($elem, ($array[$bottom])))
                    return true;

        $bottom++;
    }        
    return false;
}

 if(in_multiarray(840,$arrayValue)){
    echo "value is present in the array";
 }
0

Ok I got this, I had to add $this-> before calling in_array_r function inside. I have figure it out because I set error_reporting to E_ALL and the error was: Call to undefined function in_array_r()

XardasLord
  • 1,706
  • 2
  • 18
  • 37