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 > ( > [0] => Array > ( > [0] => action: Added > [1] => quantity: 1 > [2] => item_code: RNA1 > [3] => product_name: Mens Organic T-shirt > [4] => colour: White > [5] => size: XL > ) > > [1] => Array > ( > [6] => action: Subtracted > [7] => quantity: 7 > [8] => item_code: RNC1 > [9] => product_name: Kids Basic T-shirt > [10] => colour: Denim Blue > [11] => size: 3-4y > ) > > [2] => Array > ( > [12] => action: Added > [13] => quantity: 20 > [14] => item_code: RNV1 > [15] => product_name: Gift Voucher > [16] => style: Mens > [17] => value: £20 > ) > > )