views:

91

answers:

3

Hi,

I am using below code to find an array inside parent array but it is not working that is retuning empty even though the specified key exits in the parent array

$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();

foreach($cards_parent as $key => $card)
{
    if ($key === 'Cards')
    {
        $cards[] = $cards_parent[$key];
        break;
    }
}

Do you know any array function that will search parent array for specified key and if found it will create an array starting from that key.

Thanks

+1  A: 

you want array_key_exists()

takes in a needle (string), then haystack (array) and returns true or false.

in one of the comments, there is a recursive solution that looks like it might be more like what you want. http://us2.php.net/manual/en/function.array-key-exists.php#94601

contagious
A: 

Hi,

Could you please put a print_r($feedData); up, I ran the below code

<?php
 $feedData = array('BetradarLivescoreData' => array('Sport' => array('Category' => array('Tournament' => array('Match' => array('Cards' => array('hellow','jwalk')))))));
 $cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();

 foreach($cards_parent as $key => $card)
 {
     if ($key === 'Cards')
     {
         $cards[] = $card;
         break;
     }
 }
 print_r($cards);

And it returned a populated array:

Array ( [0] => Array ( [0] => hellow [1] => jwalk ) )

So your code is correct, it may be that your array $feedData is not.

Regards Luke

Luke
A: 

here you can use recursion:

function Recursor($arr)
{
 if(is_array($arr))
 {
  foreach($arr as $k=>$v)
  {
   if($k == 'Cards')
   {
     $_GLOBAL['cards'][] = $card;
   } else {
     Recursor($arr[$k]);
   }
  }
 }
}

$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$_GLOBAL['cards'] = array();
Recursor($cards_parent);
GOsha
Uuuuh, `$_GLOBAL`... >_< You should really `return` instead.
deceze
No. I shouldn`t. I need to pass all array. If return - recursion will be interrupted. $_Global is here to rememder finded values and to go to the end of array.
GOsha
It is perfectly possible to return and merge values throughout recursive calls. All your recursive invocations return implicitly anyway. At least use a static variable if you have to.
deceze