0

我有一个类似的数组:

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)

)

我不知道如何解决我的麻烦...有人可以帮助我吗?非常感谢大家!

4

1 回答 1

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);
于 2012-12-14T21:11:36.557 回答