php - 如何通过对象数组中的特定关键字搜索值并在 Laravel 中获取?
问题描述
如何按关键字搜索对象数组并获取该对象集(如果存在)。例如 -
array(
[0] => Object
(
[id] => 123
[label] => 'Jone Due'
[title] => 'Bangladeshi Laravel Expert'
)
[1] => Object
(
[id] => 234
[label] => 'Jone Due'
[title] => 'Bangladeshi Singer'
)
[2] => Object
(
[id] => 345
[label] => 'Jone Due'
[title] => 'Bangladeshi Actor'
)
....
);
我想title
用关键字搜索Laravel
,我想得到的结果——
array(
[0] => Object
(
[id] => 123
[label] => Jone Due
[title] => Bangladeshi Laravel Expert
)
);
可能吗?
解决方案
接下来试试。这个对我有用:
$i = 0; // counter
$ar = []; // array of indexes of success objects
$ar2 = []; // result array of objects which title has 'Laravel' inside
// $obj_ar must be consists of objects (it should has some checking code for that requirement)
// filling an array of indexes $ar
foreach ($obj_ar as $obj_1){
if (strstr($obj_1->title,'Laravel')) array_push ($ar, $i);
$i++;
}
// building a result array of objects
$count_ar = count($ar);
if ($count_ar>0) {
for($o = 0; $o < $count_ar; $o++){
array_push ($ar2, $obj_ar[$o]);
}
}
// result array of objects
echo '<pre>';
print_r($ar2);
echo '</pre>';
或者更快的方式:
$i = 0; // counter
$ar2 = []; // result array of objects which title has 'Laravel' inside
// $obj_ar must be consists of objects (it should has some checking code for that requirement)
// filling an array of indexes $ar
foreach ($obj_ar as $obj_1){
if (strstr($obj_1->title,'Laravel')) array_push ($ar2, $obj_ar[$i]);
$i++;
}
// result array of objects
echo '<pre>';
print_r($ar2);
echo '</pre>';
推荐阅读
- azure - 发布 URL https://waws-prod-am2-xxx.publish.azurewebsites.windows.net/ 无法访问
- python - torch.cat 沿负维度
- python - 创建新模型对象时出现 IntegrityError
- bazel - 解析 Bazel 构建事件协议以搜索构建失败的目标和错误消息的最佳方法是什么?
- c - 使用联合类型成员时的奇怪输出
- oracle - 创建具有固定时间部分的时间戳
- sql - 数据仓库建模问题
- javascript - 使用 ReactJs 映射获取的对象时出错
- php - Laravel 8 - 创建虚拟数据时找不到模型工厂类
- bootstrap-4 - Bootstrap v4 媒体查询在 Chrome 开发工具设备工具中不起作用