php数组组合

标签 php arrays multidimensional-array concatenation

我有下一个数组:

Array
(
    [0] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [plan_payment_type_id] => 171
            [payment_type_id] => 4
        )
    [1] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [plan_payment_type_id] => 172
            [payment_type_id] => 5
        )
    [2] => Array
        (
            [id] => 161
            [payment_period] => Weekly
            [plan_payment_type_id] => 173
            [payment_type_id] => 9
        )
)

我需要按 id 对这个数组进行分组。我怎样才能以最好的方式做到这一点? 我的输出应该是:

Array
(
    [0] => Array
        (
            [id] => 160
            [payment_period] => Monthly
            [payment_types] => Array(
                [0] => Array(
                    [plan_payment_type_id] => 171
                    [payment_type_id] => 4
                )
                [1] => Array(
                    [plan_payment_type_id] => 172
                    [payment_type_id] => 5
                )
            )
        )
    [1] => Array
        (
            [id] => 161
            [payment_period] => Weekly
            [payment_types] => Array(
                [0] => Array(
                    [plan_payment_type_id] => 173
                    [payment_type_id] => 9
                )
            )
        )
)

非常感谢。

最佳答案

像这样:

$output = array();
$id_array = array();
$i = 0;
foreach($input as $key=>$val) {
        if(array_key_exists($val['id'],$id_array)) {
                $pos = $id_array[$val['id']];
                $output[$pos]['payment_types'][] = array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']);
        } else {
                $output[$i] = array('id' => $val['id'],'payment_period' => $val['payment_period'],'payment_types' => array(array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id'])));
                echo "Adding ",$val['id'],"\n";
                $id_array[$val['id']] = $i; 
                $i++;
        }   
}

Working link

关于php数组组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3941084/

相关文章:

php - 在 PHP 应用程序中保持数据库凭据的安全

javascript - 单击 checkAll 复选框时,将其对象推送到另一个数组对象中并从现有数组中删除

php - 从多维数组数据生成json字符串

php - 用 PHP 实现 ROT13

php - 如何使用选择框从数据库行 symfony2 中获取数据

PHP:像在 Python 中一样获取数组值?

arrays - 对 Swift 数组声明感到困惑

python - 如何根据 python3 中元素的值将平面列表转换为列表列表?

java - 在 spring bean 中注入(inject) 2D int 数组

php - ProviderRepository.php 中的 FatalErrorException 第 208 行 : Class 'Illuminate\Html\HtmlServiceProvider' not found