首页 > 解决方案 > 从数组中返回对象项

问题描述

我需要遍历一个数组并返回该项目对象的属性。

我的数组有这种格式:

Arquivo mongodb 数组链接

我尝试使用以下功能解决此问题:

public function returnObjectByDayAndTrip ($ links, $ trip, $ dayOperation)
    {
        $ newArray = array_filter ($ links, function ($ obj) use ($ trip, $ dayOperation) {
            if ($ obj ['trip'] == $ trip && $ obj ['dayOperation'] === $ dayOperation) {
                return true;
            } else {
                return false;
            }
        });

        if (isset ($ newArray [0])) {
            return $ newArray [0] ['url'];
        } else {
            return null;
        }
    }

并称她为使用:

$link-> week = $ this-> returnObjectByDayAndTrip ($ links, $ trip, 'week');

$links我的图像数组在哪里,$trip是我需要获取的日期,而“周”是我需要获取的操作日。

例如,当项目是数组的 [3] 时,我的错误就会发生,当它是第一个时,从位置1开始,一切都更有效,不再有效。

我的回报var_dump

object(stdClass)#632 (4) { ["week"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-em-dias-uteis " ["星期六"]=> NULL ["星期日"]=> NULL ["changeDestiny"]=> NULL }

array(1) { [0]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#477 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e8" } ["url"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-em-dias-uteis" ["dayOperation"]=> string(4) "week" ["trip"]=> string(5) "tripA" } } 

array(1) { [2]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#479 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e6" } ["url"]=> string(73) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-no-sabado" ["dayOperation"]=> string(8) "saturday" ["trip"]=> string(5) "tripA" } } 

array(1) { [4]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#481 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e4" } ["url"]=> string(74) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-santa-ruth-no-domingo" ["dayOperation"]=> string(6) "sunday" ["trip"]=> string(5) "tripA" } } 

array(1) { [1]=> array(4) { ["_id"]=> object(MongoDB\BSON\ObjectId)#478 (1) { ["oid"]=> string(24) "5b3f74ad6ae83d00223504e7" } ["url"]=> string(77) "/horario-de-onibus-010-bela-vista-santa-ruth-destino-bela-vista-em-dias-uteis" ["dayOperation"]=> string(4) "week" ["trip"]=> string(5) "tripB" } } 

我需要根据传递给函数的特殊性返回对象的 url。在我的数组中,必然只有 1 个项目或没有满足报告信息的项目,即总是有结果或没有。

标签: phplaravel

解决方案


我能够解决使用current ()它返回数组的第一个位置,所以它看起来像这样:

public function returnObjectByDayAndTrip ($ links, $ trip, $ dayOperation)
{
    $ newArray = array_filter ($ links, function ($ obj) use ($ trip, $ dayOperation) {
        if ($ obj ['trip'] == $ trip && $ obj ['dayOperation'] === $ dayOperation) {
            return true;
        } else {
            return false;
        }
    });


    if (count ($ newArray)> = 1) {
        return current ($ newArray) ['url'];
    } else {
        return null;
    }
}

可能有更好的方法来做到这一点,我什至接受这种新方法,但这样它解决了我的问题。这里的理想是加入array_maparray_filter变得强大。


推荐阅读