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

尝试从多维数组中获取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 '??'

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器