Distribute array row data to make multiple new rows



PHP Snippet 1:

$data= [
    [
        "price_in_dollar" => 1000,
        "price_in_euro" => 1000,
        "price_in_pound" => 1000,
        "price_in_rupee" => 1000,
        "toy_id" => 1,
        "toy_name" => "Truck"
    ],
    [
        "price_in_dollar" => 1000,
        "price_in_euro" => 1000,
        "price_in_pound" => 1000,
        "price_in_rupee" => 1000,
        "toy_id" => 2,
        "toy_name" => "Bicycle"
    ]
];

$cnt = 0;

foreach($data as $r) {
    foreach($r as $key => $value) {

        if ($key === 'toy_name') {
            $cars[$cnt]['toy'] =  $value ;
        }
        else if ($key === 'toy_id') {
            $cars[$cnt]['toy_id'] =  $value;
        }
        else {
            $cars[$cnt]['slug'] =  $key ;
            $cars[$cnt]['rate'] =  $value;
        }
    }
    
    $cnt++;
}

// display result
print_r($cars);

PHP Snippet 2:

foreach($data as $r) {
foreach($r as $key => $value) {

    if ($key === 'toy_name') {
        $cars[]['toy'] =  $value ;
    }
    else if ($key === 'toy_id') {
        $cars[]['toy_id'] =  $value;
    }
    else {
        $cars[]['slug'] =  $key ;
        $cars[]['rate'] =  $value;
    }
}

PHP Snippet 3:

$result = [];
foreach ($data as $row) {
    ['toy_id' => $id, 'toy_name' => $name] = $row;
    unset($row['toy_id'], $row['toy_name']);
    foreach ($row as $slug => $rate) {
        $result[] = compact(['id', 'name', 'slug', 'rate']);
    }
}
var_export($result);