数组到没有索引的子

时间:2017-01-25 11:38:31

标签: php arrays json

我有这个代码,基本上需要一些行,并以4个组的形式放入一个数组

最初数据采用以下格式:

line1
line2
line3
line4
line5
line6
line7
line8

并使用此代码将行传递给数组:

$addresses = [];
foreach (preg_split("/((\r?\n)|(\r\n?))/", $nodes) as $line) {
    $temp[] = trim($line);
    if(count($temp) == 4){
        array_push($addresses,[
                    'ADDRESS' => $temp[0],
                    'STREET_NAME' => $temp[1],
                    'TOWN_NAME' => $temp[2],
                    'POST_CODE' => $temp[3]
                ]);
      $temp = [];
  }
}
var_dump(json_encode($addresses,JSON_PRETTY_PRINT));

但结果不是我想要的......:

{
  "1": {
      "ADDRESS": "10",
      "STREET_NAME": "TRIQ ID-DAR TA` PULTU",
      "TOWN_NAME": "BIRZEBBUGA",
      "POST_CODE": "BBG 1810"
  },
  "2": {
      "ADDRESS": "12",
      "STREET_NAME": "TRIQ ID-DAR TA` PULTU",
      "TOWN_NAME": "BIRZEBBUGA",
      "POST_CODE": "BBG 1810"
  }
}

我不想索引...

我需要这样的东西:

[
{
  "ADDRESS": "10",
  "STREET_NAME": "TRIQ ID-DAR TA` PULTU",
  "TOWN_NAME": "BIRZEBBUGA",
  "POST_CODE": "BBG 1810"
},
{
  "ADDRESS": "12",
  "STREET_NAME": "TRIQ ID-DAR TA` PULTU",
  "TOWN_NAME": "BIRZEBBUGA",
  "POST_CODE": "BBG 1810"
}
]

关于这个错误的任何想法???

1 个答案:

答案 0 :(得分:1)

这将创建您要求的内容

$nodes = 'line1
line2
line3
line4
line5
line6
line7
line8
';

$addresses = [];
foreach (preg_split("/((\r?\n)|(\r\n?))/", $nodes) as $line) {
    $temp[] = trim($line);
    if(count($temp) == 4){
        $obj = new stdClass();
        $obj->ADDRESS =  $temp[0];
        $obj->STREET_NAME = $temp[1];
        $obj->TOWN_NAME = $temp[2];
        $obj->POST_CODE = $temp[3];

        $addresses[] = $obj;
        $temp = [];
    }
}
var_dump(json_encode($addresses,JSON_PRETTY_PRINT));

结果:

string(266) "[
    {
        "ADDRESS": "line1",
        "STREET_NAME": "line2",
        "TOWN_NAME": "line3",
        "POST_CODE": "line4"
    },
    {
        "ADDRESS": "line5",
        "STREET_NAME": "line6",
        "TOWN_NAME": "line7",
        "POST_CODE": "line8"
    }
]"

但是当您查看编码的数据然后解码回PHP数据类型时,您仍然会以数字方式对对象进行索引,因为数组必须有索引。当您将此数据发送到javascript时,这适用于PHP和等效的javascript

print_r(json_decode(json_encode($addresses)));

结果

Array
(
    [0] => stdClass Object
        (
            [ADDRESS] => line1
            [STREET_NAME] => line2
            [TOWN_NAME] => line3
            [POST_CODE] => line4
        )

    [1] => stdClass Object
        (
            [ADDRESS] => line5
            [STREET_NAME] => line6
            [TOWN_NAME] => line7
            [POST_CODE] => line8
        )

)