-3

We have wrote this function to return specific array

public function searchArrayMultidimensional($array,$key){
    foreach($array as $k=>$row){
        if($k==$key){
            if(is_array($row)){
                return $row;
            }else{
                continue;
            }
        }else{
            $this->searchArrayMultidimensional($row,$key);
        }
    }
}

Not issue is while we print inside foreach on this line return $row; it returns perfect result,

while we call this function or print_r this function using

print_r($this->searchArrayMultidimensional($giftProducts,'sku'));

its not resulting an array

Actual result : (blank)

Expected result :

Array
(
    [0] => HHM1601
    [1] => HHM1602
    [2] => HHM1603
    [3] => HHM1604
    [4] => HHM1605
    [5] => HHM1606
    [6] => HHM1607
)

**EDITED **

This is the actual array :

original array link

Array
(
    [0] => Array
        (
            [196] => Array
                (
                    [sku] => Array
                        (
                            [0] => HHM1601
                            [1] => HHM1602
                            [2] => HHM1603
                            [3] => HHM1604
                            [4] => HHM1605
                            [5] => HHM1606
                            [6] => HHM1607
                        )

                    [qty] => 3.0000
                    [rule_id] => 196
                )

        )

    [1] => Array
        (
            [sku] => IS1617
            [qty] => 1
            [auto_add] => 1
            [rule_id] => 263
            [qtyIncreased] => 1
        )

)
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62

1 Answers1

1

You should change two things in your code: write $k===$key instead of $k==$key and in else statement write return $this->searchArrayMultidimensional($row,$key);

finally your code should look like:

public function searchArrayMultidimensional($array,$key){
    foreach($array as $k=>$row){
        if($k===$key){
            if(is_array($row)){
                return $row;
            }else{
                continue;
            }
        }else{
            return $this->searchArrayMultidimensional($row,$key);
        }
    }
}

Note:

your should write === comparison operator because your first key is 0 and when you compare 0 to string with == operator it return true and your response would be:

Array ( [196] => Array ( [sku] => Array ( [0] => HHM1601 [1] => HHM1602 [2] => HHM1603 [3] => HHM1604 [4] => HHM1605 [5] => HHM1606 [6] => HHM1607 ) [qty] => 3 [rule_id] => 196 ) )

not

Array ( [0] => HHM1601 [1] => HHM1602 [2] => HHM1603 [3] => HHM1604 [4] => HHM1605 [5] => HHM1606 [6] => HHM1607 )
godot
  • 3,422
  • 6
  • 25
  • 42