php - 从数组中返回对象项
问题描述
我需要遍历一个数组并返回该项目对象的属性。
我的数组有这种格式:
我尝试使用以下功能解决此问题:
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 个项目或没有满足报告信息的项目,即总是有结果或没有。
解决方案
我能够解决使用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_map
并array_filter
变得强大。
推荐阅读
- ruby-on-rails - 如何使用 Rails 实例的公共方法执行?在 if-else 中
- javascript - 为什么我的代码没有过滤数组?我错过了什么?
- javascript - 在javascript中动态地将用户输入字段中的数据添加到表中
- c# - Selenium Webdriver 如何避免对 ChormeDriver 使用“no-sandbox”模式来防止超时
- php - Symfony 在 parameters.yml 中存储加密的数据库密码
- android - 系统环境变量未出现
- mysql - 选择回答了所有问题的用户
- php - PHP - 联系表格不发送数据
- angular - 角 6 | Webpack 生产构建错误
- gdb - gdb 读取核心文件后退出