0

我的数组是这样的:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => keybord
        )

    [1] => Array
        (
            [id] => 2
            [name] => b
            [hardware_type] => mouse
        )

    [2] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => mouse
        )

    [3] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => moniter
        )

    [4] => Array
        (
            [id] => 2
            [name] =>b
            [hardware_type] => keyboad
        )

)

像这样需要输出我只想合并硬件类型

Array(
    [0] => Array

        (
            [id] => 1
            [name] => a
            [hardware_type] => keybord, mouse, moniter
        )
[1] => Array
    (
            [id] => 1
            [name] => b
            [hardware_type] => keyboard, mouse
        )

 )
4

1 回答 1

0

$array您描述的输入数组在哪里,您$newarray想要的输出数组在哪里,并假设 的每个值都与您的示例输入中id的相同:name

$temp = array();

foreach ($array as $item) {
  $temp[$item['id']] = array('id' => $item['id'], 'name' => $item['name']);
  if (empty($newarray[$item['id']]['hardware_type']))
    $temp[$item['id']]['hardware_type'] = $item['hardware_type'];
  else 
    $temp[$item['id']]['hardware_type'] .= ', ' . $item['hardware_type'];
}

$newarray = array_values($temp);

如果您希望hardware_type是一个数组而不是逗号分隔的字符串列表,请改为执行以下操作:

$temp = array();

foreach ($array as $item) {
  $temp[$item['id']] = array('id' => $item['id'], 'name' => $item['name']);
  $temp[$item['id']]['hardware_type'][] = $item['hardware_type'];
}

$newarray = array_values($temp);
于 2012-12-03T05:52:24.503 回答