如何找到多维数组中最后出现的项的键? [英] How can I find the key of the last occurrence of an item in a multidimensional array?

查看:60
本文介绍了如何找到多维数组中最后出现的项的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在以下数组中找到与(id = 100001203541047)的最后一次出现对应的键:

I need to find the key that corresponds to the last occurrence of (id = 100001203541047) in the following array:

[0] => Array
        (
            [id] => 10152583762905798_10152583800415798
            [from] => Array
                (
                    [id] => 100001203541047
                    [name] => Gangareddy Chealimealla
                )

            [message] => Desi Flipkart
            [created_time] => 2014-07-30T07:30:34+0000
            [like_count] => 0
            [user_likes] =>
            [can_comment] => 1
        )

    [1] => Array
        (
            [id] => 10152583762905798_10152583786375798
            [from] => Array
                (
                    [id] => 100001430479186
                    [name] => Pratik Das
                )

            [message] => flipkart rules! (y)
            [created_time] => 2014-07-30T07:16:56+0000
            [like_count] => 0
            [user_likes] =>
            [can_comment] => 1
        )

    [2] => Array
        (

            [id] => 10152583762905798_10152583802415798
            [from] => Array
                (
                    [id] => 100001203541047
                    [name] => Gangareddy Chealimealla
                )

            [message] => Desi Flipkart
            [created_time] => 2014-07-30T08:30:34+0000
            [like_count] => 0
            [user_likes] =>
            [can_comment] => 1
        )

我尝试了以下代码,但它返回2个职位。

I tried the following code, but it's returning 2 positions.

 foreach($arr as $key => $array)
 {
     if ( $array['from']['id'] === $id)
         echo $key."\n\n";
     }
 }

为什么不只显示最后一个?

Why doesn't this only show the last one?

推荐答案

您已经编写的代码几乎可以正常工作。问题在于,每次在foreach循环中遇到与ID匹配的键时,它将立即立即打印键。

The code you already wrote almost works. The problem is that it will just immediately print the key each time it encounters one that matches the id during the foreach loop.

foreach($arr as $key => $array) {
    if ( $array['from']['id'] === $id) {
        echo $key."\n\n";
    }
}

如果您将密钥存储在变量中,则循环结束后,变量中的值将是最后一个,您只需打印出来即可。

If instead you store the key in a variable, then after the loop is finished, the value in the variable will be the last one, and you can just print that.

$last = "";
foreach($arr as $key => $array) {
    if ( $array['from']['id'] === $id) {
        $last = $key;
    }
}
echo $last."\n\n";

这篇关于如何找到多维数组中最后出现的项的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆