PHP多维数组操作.获取具有相同键的数组形式的数据



我有一个包含如下内容的数组的结果:

array(
   [0]=>array(
       ["id"]=>56,
       ["name"]=>"john",
       ["company_id"]=>1,
       ["profession"]=>"IT";
   )
   [1]=>array(
       ["id"]=>57,
       ["name"]=>"jane",
       ["company_id"]=>2,
       ["profession"]=>"QC Assistant";
   )
   [2]=>array(
       ["id"]=>58,
       ["name"]=>"Bert",
       ["company_id"]=>1,
       ["profession"]=>"IT Specialist";
   )
   [3]=>array(
       ["id"]=>60,
       ["name"]=>"Roy",
       ["company_id"]=>3,
       ["profession"]=>"Plumber";
   )
)

现在我的问题是我需要搜索所有company_id = 1,并把它在数组形式与所有他的键和值在里面。

$new_arr = array();
foreach ($arr as $a)
    if ($a['company_id']==1)
        $new_arr[] = $a;
print_r($new_arr);
结果:

Array
(
    [0] => Array
        (
            [id] => 56
            [name] => john
            [company_id] => 1
            [profession] => IT
        )
    [1] => Array
        (
            [id] => 58
            [name] => Bert
            [company_id] => 1
            [profession] => IT Specialist
        )
)

OR,如果您不希望company_id包含在新数组中,其中company_id始终为1,则

$new_arr = array();
foreach ($arr as $a)
    if ($a['company_id']==1) {
        unset($a['company_id']);
        $new_arr[] = $a;
    }
print_r($new_array);
结果:

Array
(
    [0] => Array
        (
            [id] => 56
            [name] => john
            [profession] => IT
        )
    [1] => Array
        (
            [id] => 58
            [name] => Bert
            [profession] => IT Specialist
        )
)

您也可以使用array_filter():

$a = array_filter($a, function($v){return $v['company_id']==1;});

相关内容

  • 没有找到相关文章

最新更新