0

I am using this function to create array:

$products = $request->input('product');
    $productinput = array();
    foreach (array_keys($products) as $fieldKey) {
        foreach ($products[$fieldKey] as $key=>$value) {
             $productinput[$key][$fieldKey] = $value;
        }
    } 
    return $productinput;

and this is what it is returning via json_encode:

[   
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},    
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]

Now I need to rename product_quantity to quantity and product_price to price. Is there anyone to help me out?

icc97
  • 10,009
  • 8
  • 64
  • 83
Sark
  • 299
  • 2
  • 19
  • Add new key, unset previous. I don't see __any trouble__ here. – u_mulder Nov 12 '17 at 12:40
  • 1
    you can find you answer here https://stackoverflow.com/questions/9605143/how-to-rename-array-keys-in-php – Dhairya Lakhera Nov 12 '17 at 12:42
  • 1
    Just for novelty value this will take your output array and rename the keys as you want (assuming your output array is called `$products`): `array_map(function ($product) { return array_reduce(array_keys($product), function($carry, $item) use ($product) { $key = preg_match('/price|quantity/', $item) ? str_replace('product_', '', $item) : $item; $carry[$key] = $product[$item]; return $carry; },[]);}, $products); ` – icc97 Nov 12 '17 at 13:42

0 Answers0