首页 > 解决方案 > 如何通过对象数组中的特定关键字搜索值并在 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
    )
);

可能吗?

标签: phplaravel

解决方案


接下来试试。这个对我有用:

 $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>';

推荐阅读