I have been given an array which is holding a series of strings. I have been tasked with converting this array of strings into an associative array with key-value pairs with simple code. So far, I have managed to split the strings into their own elements using the array_chunk function so that they’re in their own arrays, and my goal is to convert the elements in their own arrays into key-value pairs. However, given my very little amount of experience when it comes to PHP i’m not sure how I can go about doing this. Any help or advice is much appreciated!
> <?php > > $arr = array( > "action: Added; quantity: 1; item_code: RNA1; product_name: Mens Organic T-shirt; colour: White; size: XL", > "action: Subtracted; quantity: 7; item_code: RNC1; product_name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y", > "action: Added; quantity: 20; item_code: RNV1; product_name: Gift Voucher; style: Mens; value: £20", > ); > > // Using json_encode for square brakets; makes for easier formatting. > json_encode($arr); > // Split the array into strings. > $imploded = implode("; ", $arr); > > //echo $imploded; > > // Seperate the strings by the ";" character. > $exploded = explode("; ",$imploded); > // This gives me the keys and pairs in the same index. > > //print_r($exploded); > > // Split the array for every 6 elements. > $chunked = array_chunk($exploded,6,true); > > print_r($chunked);
This is what I want the arrays to look like:
'action' => '', 'quantity' => '', 'item_code' => '', 'product_name' => '', 'colour' => '', 'size' => '',
However, this is how the arrays currently look.
> > Array > ( >  => Array > ( >  => action: Added >  => quantity: 1 >  => item_code: RNA1 >  => product_name: Mens Organic T-shirt >  => colour: White >  => size: XL > ) > >  => Array > ( >  => action: Subtracted >  => quantity: 7 >  => item_code: RNC1 >  => product_name: Kids Basic T-shirt >  => colour: Denim Blue >  => size: 3-4y > ) > >  => Array > ( >  => action: Added >  => quantity: 20 >  => item_code: RNV1 >  => product_name: Gift Voucher >  => style: Mens >  => value: £20 > ) > > )