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));
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4968f-44d29.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4968f-44d29.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?