duanpu1963
2013-02-12 21:46
浏览 49
已采纳

尝试从多维数组中获取Key的值

I have an array thus (got this using var_dump):

array
  0 => 
    array
      'post_id' => string '6' (length=1)
  1 => 
    array
      'post_id' => string '9' (length=1)

I want to get the key when I have just the post_id. For example, I want '0' returned if I have '6' and '1' if I have '9'. I have tried:

$key = array_keys($subs, array_keys($subs[??], 6));

given that the $subs is the array. The issue is, I don't know how to iterate through the array 'within' the 'parent' array, hence, the '??'

图片转代码服务由CSDN问答提供 功能建议

我有一个数组(使用 var_dump 得到这个): \ n

  array 
 0 =>  
 array 
'post_id'=> 字符串'6'(长度= 1)
 1 =>  
 array 
'post_id'=> 字符串'9'(长度= 1)
   
 
 

当我只有 post_id 时,我想获取密钥。 例如,如果我有'6',我希望'0'返回,如果我'9',我想要'1'。 我试过了:

  $ key = array_keys($ subs,array_keys($ subs [??],6)); 
   \  n 
 

假设 $ subs 是数组。 问题是,我不知道如何遍历“父”数组内的数组,因此,'??'

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doubengshao8872 2013-02-12 22:29
    已采纳

    I would use array_filter() and use to do this. Like this:

    $array; // your array
    $needle; // the value you are looking for
    $filtered_array = array_filter($array, function ($element) use ($needle) {
        return ($element['post_id'] === $needle);
    });
    
    $matching_keys = array_keys($filtered_array);
    

    The array_filter() will filter down the input array to only those array element arrays that have a value for post_id that matches the value of $needle. You can use array_keys to get the key values for the remaining element(s) after the filter has been applied.

    打赏 评论
  • doraemon0769 2013-02-12 22:03
    $post_id_to_find = '6';
    $key = '';
    foreach ($subs as $k1 => $v1)
    {
        foreach ($v1 as $k2 => $v2)
        {
            if ($post_id_to_find == $v2)
            {
                $key = $k1;
                break;
            }
        }
    }
    

    Essentially what this code does is loop through the outer array and for each element loop through inner array, and if it finds the post id you want it'll set a variable that was initalized outside of the loops so after you break out of the loops you'll have the appropriate key.


    EDIT

    This is actually a pretty crappy answer, I realized you don't really need the inner loop since you know what key you want to check in the inner arrays... Anyway it seems like you used another answer, so this is pretty much moot.

    打赏 评论

相关推荐 更多相似问题