多维数组中的php数组操作。以数组形式获取数据,所有数据都具有相同的键

时间:2014-05-07 18:31:07

标签: php arrays multidimensional-array

我有一个包含这样的数组的结果:

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并将其以数组形式放入其中包含所有键和值。

2 个答案:

答案 0 :(得分:0)

您也可以使用array_filter()

执行此操作
$a = array_filter($a, function($v){return $v['company_id']==1;});

答案 1 :(得分:0)

$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
        )

)

或者,如果您不希望新数组中包含company_idcompany_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
        )

)