PHP, Converting a string using brackets to an array

I request an API and send a JSON response, which I then change to an array. This part works fine, but the API sends the information in a rather unfriendly format.

I will insert the part that I'm having problems with. Essentially, I am trying to change each similar key into my own array.

Array ( [name] => Name [address] => 123 Street Rd [products[0][product_id]] => 1 [products[0][price]] => 12.00 [products[0][name]] => Product Name [products[0][product_qty]] => 1 [products[1][product_id]] => 2 [products[1][price]] => 3.00 [products[1][name]] => Product Name [products[1][product_qty]] => 1 [systemNotes[0]] => Note 1 [systemNotes[1]] => Note 2 ) 

Now what I would like to do is do it something like this:

 Array ( [name] => Name [address] => 123 Street Rd [product] => Array ( [0] => Array ( [product_id] => 1 [price] => 12.00 [name] => Product Name [product_qty] => 1 ) [1] => Array ( [product_id] => 2 [price] => 3.00 [name] => Product Name [product_qty] => 1 ) [systemNotes] => Array ( [0] => Note 1 [1] => Note 2 ) ) 

Is there any practical way to do this?

Thanks!

+4
source share
2 answers

Links are your friend here:

 $result = array(); foreach ($inputArray as $key => $val) { $keyParts = preg_split('/[\[\]]+/', $key, -1, PREG_SPLIT_NO_EMPTY); $ref = &$result; while ($keyParts) { $part = array_shift($keyParts); if (!isset($ref[$part])) { $ref[$part] = array(); } $ref = &$ref[$part]; } $ref = $val; } 

Demo


However, there is another, much simpler way, although it is slightly less effective in terms of functional complexity:

 parse_str(http_build_query($inputArray), $result); 

Demo

+5
source

With $array your original array:

 $new_array = array("name" => $array["name"], "address" => $array["address"]); foreach($array["products"] AS $product) { $new_array["product"][] = array( "product_id" => $product["produit_id"], "price" => $product["price"], "name" => $product["name"], "product_qty" => $product["product_qty"]); } foreach($array["systemNotes"] AS $note) { $new_array["systemNotes"][] = $note; } 

It is just viewing and creating a new structure. ^^

Edit: Something in common can be done recursively. Calling the same function as the is_array element being is_array , and building a new array according to the keys and values. Looks like a file system ^^

0
source

Source: https://habr.com/ru/post/1492196/


All Articles