PHP:以递归方式操作数组值作为键

时间:2017-03-31 07:28:51

标签: php arrays

我得到了这个数组:

array:2 [▼
  0 => array:1 [▼
    0 => array:7 [▼
     "id" => "1"
     "producer" => "Samsung"
     "model" => "LE22B541C4W"
     "category" => "1"
     "production_date" => "2009-05-08"
     "status" => "Discontinued"
     "type" => "LCD"
     ]
  ]
  1 => array:1 [▼
    0 => array:7 [▼
     "id" => "2"
     "producer" => "Samsung"
     "model" => "P24FHD"
     "category" => "1"
     "production_date" => "0000-00-00"
     "status" => "Discontinued"
     "type" => "LCD"
    ]
  ]
 [...]
]

我想把每个数组的“ID”值作为主键并删除像这样无用的键

array:2 [
  1 => array:7 [
    "id" => "1"
    "producer" => "Samsung"
    "model" => "LE22B541C4W"
    "category" => "1"
    "production_date" => "2009-05-08"
    "status" => "Discontinued"
    "type" => "LCD"
    ]
  2 => array:7 [
   [...]

到目前为止,我只是使用这个简单的查询和for循环来填充数组:

foreach ($compatibility as $compElement) {

        $sql = "SELECT * FROM product WHERE ID = '$compElement';";

        $em = $this->getDoctrine()->getManager();
        $stmt = $em->getConnection()->prepare($sql);
        $stmt->execute();
        $thisElement = $stmt->fetchAll();

        $compArray[] = $thisElement;

    }

1 个答案:

答案 0 :(得分:1)

如果您不想更改阵列的填充方式,可以执行以下操作:

$result = call_user_func_array(
               'array_merge_recursive',
                $array
            );

输出

array(2) {
  [0]=>
  array(7) {
    ["id"]=>
    string(1) "1"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(11) "LE22B541C4W"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "2009-05-08"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
  [1]=>
  array(7) {
    ["id"]=>
    string(1) "2"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(6) "P24FHD"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "0000-00-00"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
}