紧凑的多维数组

时间:2012-12-14 20:54:37

标签: php multidimensional-array

我有一个类似的阵列:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Mario
        [type] => Doctor
        [operations] => brain
        [balance] => 3.00
    )

[1] => Array
    (
        [id] => 3
        [name] => Luca
        [type] => Doctor
        [operations] => hearth
        [balance] => 6.00
    )

[2] => Array
    (
        [id] => 3
        [name] => Luca
        [type] => Doctor
        [operations] => hands
        [balance] => 4.00
    )

[3] => Array
    (
        [id] => 3
        [name] => Luca
        [type] => Doctor
        [operations] => foots
        [balance] => 1.00
    )

)

我必须将它合并为id,因此只获取数组(0和1)的2个元素,并且Luca(id 3)必须统一用于操作,在新数组中,类似于此,因此在将来打印时会更清楚操作统一而不分。

[...]
)
[1] => Array
(
  [id] => 3
  [name] => luca
  [type] => doctore
  [operations] => Array (6.00 hearts,
                         4.00 hands,
                         1.00 foots)

我无法想象如何解决我的麻烦......有人可以帮我吗?非常感谢大家!

1 个答案:

答案 0 :(得分:1)

<?php

$input = array(
    array('id' => 1, 'name' => 'Mario', 'type' => 'Doctor', 'operations' => 'brain', 'balance' => 3.00),
    array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hearth', 'balance' => 6.00),
    array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hands', 'balance' => 4.00),
    array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'foots', 'balance' => 1.00),
);

$output = array();

foreach ($input as $person)
{
    // Add the person to the output, if needed.
    if (array_key_exists($person['id'], $output) === false)
    {
        $output[$person['id']] = 
            array( 
                'id' => $person['id'],
                'name' => $person['name'],
                'type' => $person['type'],
                'operations' => array(),
            );
    }

    // Add the operation to the array of operations.
    $output[$person['id']]['operations'][] =
        array(
            'type' => $person['operations'],
            'balance' => $person['balance'],
        ));
}

foreach ($output as $person)
{
    if (count($person['operations']) === 1)
    {
        // If the array contains only 1 item, pull it out of the array.
        $output[$person['id']]['operations'] = $person['operations'][0];
    }
}

print_r($output);