PHP找到多维数组最后一次出现 [英] PHP find last occurrence from multidimensional array

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

问题描述

我很新的PHP,尝试一些基本的PHP脚本。我需要找到以下阵列(ID = 100001203541047)最后一次出现

I am very new to php, trying few basic php scripts. I need to find 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
        )

我试过以下code,但其返回2个位置。

I tried following code but its returning 2 positions.

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

任何帮助吗?

感谢

推荐答案

在code你已经写了差不多的作品。问题是,它只是立即打印键,每次遇到一个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";

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

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