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 に答える