开发者

How to find an array from parent array?

开发者 https://www.devze.com 2023-01-02 10:50 出处:网络
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

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?


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


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消