php中的多维数组重新格式化

时间:2017-08-30 09:19:28

标签: php arrays string multidimensional-array array-push

尝试达到我想要的效果。但遗憾的是,经过几个小时的努力,我无法实现这一目标。到目前为止,我尝试了什么:

$post_data = array(
    'email_address' => "sda",
    'status_if_new' => 'subscribed',
    'merge_fields' => array(

        'FNAME' => "asd",
        'LNAME' => "sad")
);
$st= "{\"Field0\":\"Value0\",\"Field1\":\"Value1\"}";
$string = str_replace(array('{','}','"'),'',$st);

$custom_array=explode(",",$string);

$len= count($custom_array);


for($i=0;$i<$len;$i++) {
    $fields = explode(":", $custom_array[$i]);

    array_push($post_data["merge_fields"],$fields);
}
echo "<pre>";
var_dump($post_data);
die("sad");

结果现在:在字符串格式化之后将该字符串推送到数组中。

array(3) {
  ["email_address"]=>
  string(3) "sda"
  ["status_if_new"]=>
  string(10) "subscribed"
  ["merge_fields"]=>
  array(4) {
    ["FNAME"]=>
    string(3) "asd"
    ["LNAME"]=>
    string(3) "sad"
    [0]=>
    array(2) {
      [0]=>
      string(6) "Field0"
      [1]=>
      string(6) "Value0"
    }
    [1]=>
    array(2) {
      [0]=>
      string(6) "Field1"
      [1]=>
      string(6) "Value1"
    }
  }
}
sad

我想要实现的目标:,但我想以不同的方式实现这一点,您可以在下面看到:

array(3) {
  ["email_address"]=>
  string(3) "sda"
  ["status_if_new"]=>
  string(10) "subscribed"
  ["merge_fields"]=>
  array(4) {
    ["FNAME"]=>
    string(3) "asd"
    ["LNAME"]=>
    string(3) "sad"
    ["Field0"]=>
    string(6) "Value0"
    ["Field1"]=>
    string(6) "Value1"
}
}
sad

如果有任何问题,请随时问我。 任何人?为了帮助我实现理想的结果? TIA。

2 个答案:

答案 0 :(得分:0)

使用$post_data["merge_fields"][$fields[0]] = $fields[1] 而不是 array_push($post_data["merge_fields"],$fields);

答案 1 :(得分:0)

$post_data = array(
'email_address' => "sda",
'status_if_new' => 'subscribed',
'merge_fields' => array(

    'FNAME' => "asd",
    'LNAME' => "sad")
);
$st= "{\"Field0\":\"Value0\",\"Field1\":\"Value1\"}";
$string = str_replace(array('{','}','"'),'',$st);


$custom_array=explode(",",$string);

$len= count($custom_array);


for($i=0;$i<$len;$i++) {
    $fields = explode(":", $custom_array[$i]);

   $post_data["merge_fields"][$fields[0]] = $fields[1];
}
echo "<pre>";
var_dump($post_data);
die("sad");