The problem of php generating an array into an array of a specific format

has an array in the following format:

$input = [
    ["vid" => 1, "v_name" => "v1", "prop" => ["pid" => 1, "p_name" => ""]],
    ["vid" => 2, "v_name" => "v2", "prop" => ["pid" => 1, "p_name" => ""]],
    ["vid" => 3, "v_name" => "v3", "prop" => ["pid" => 2, "p_name" => ""]],
];

now I"m going to return it in the following format:

$output = [
            [
            "pid" => 1,
            "p_name" => "",
            "p_v_list" => [
                [
                    "vid" => 1,
                    "v_name" => "v1"
                ],
                [
                    "vid" => 2,
                    "v_name" => "v2"
                ],
            ]
        ],
        [
            "pid" => 2,
            "p_name" => "",
            "p_v_list" => [
                [
                    "vid" => 3,
                    "v_name" => "v3"
                ]
            ]
        ]
    ];

I use foreach for stitching:

$output = [];
foreach ($input as $item) {
    $pid = $item["prop"]["pid"];
    if (!array_key_exists($pid, $output)) {
        $output[$pid] = $item["prop"];
    }
    $output[$pid]["p_v_list"][] = ["vid" => $item["vid"], "v_name" => $item["v_name"]];
}
$output = array_chunk($output, count($output))[0];

now I don"t think this method is very good, but I can"t figure out how to generate it better at the moment, so I would like to ask you if there is a good way?

thanks!
Php
Jun.06,2021

seems to be about the same,


foreach.

$result = array_reduce($input, function($result, $item) {
    if (!isset($result[$item['prop']['pid']])) {
        $result[$item['prop']['pid']] = array_merge($item['prop'], ['p_v_list' => []]);
    }
    $result[$item['prop']['pid']]['p_v_list'][] = [
        'vid' => $item['vid'],
        'v_name' => $item['v_name']
    ];
    return $result;
}, []);

print_r(array_values($result));
Menu