Best way to parse json_decoded php array

harry

New Member
#1
What would be the best way to parse stringified one dimensional array?

input array
Mã:
$inputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money[0][amount]" => 30,
  "money[0][countryCode]" => "US",
  "money[1][amount]" => 25,
  "money[1][countryCode]" => "CA",
)
desired output array
Mã:
$outputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money" => array(
    [0] => array(
      "amount" => 30,
      "countryCode" => "US"
    ),
    [1] => array(
      "amount" => 25,
      "countryCode" => "CA"
    ),
  ),
)
 

Admin

Administrator
Thành viên BQT
#2
You can convert your array in a query url and parse it ... like this
Mã:
<?php

$inputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money[0][amount]" => 30,
  "money[0][countryCode]" => "US",
  "money[1][amount]" => 25,
  "money[1][countryCode]" => "CA",
);

$url = http_build_query($inputArray);
parse_str($url, $outputArray);

print_r($outputArray);
Live example: https://3v4l.org/DAAUM
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top