Skip to content
Advertisement

Distribute array row data to make multiple new rows

I have below the 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"
    }
]

I want to create a new array from above as below

[
    {
        "toy": "Truck",
        "toy_id": 1,
        "rate": 1000,
        "slug": "price_in_dollar",
    },
    {
        "toy": "Truck",
        "toy_id": 1,
        "rate": 1000,
        "slug": "price_in_euro",
    },
    ...
    {
        "toy": "Bicycle",
        "toy_id": 2,
        "rate": 1000,
        "slug": "price_in_dollar",
    },
    {
        "toy": "Bicycle",
        "toy_id": 2,
        "rate": 1000,
        "slug": "price_in_euro",
    },
    ...

]

I have tried the below code

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;
        }
    }
}

But it only has one set of data, how can I append all data? Or any improved code to solve this?

Advertisement

Answer

your code was actually replacing a key => value pair data, not pushing a data into $cars, you can fix it like this:

$cars = [];
foreach($data as $r) {
    $singleCar = [
        "toy_id" => $r['toy_id'],
        "toy" => $r['toy_name'],
    ];
    
    foreach($r as $key => $val){
        if($key != 'toy_id' && $key != 'toy_name') {
            $singleCar['rate'] = $val;
            $singleCar['slug'] = $key;
            
            $cars[] = $singleCar;
        }
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement