简体   繁体   English

从包含相关逗号分隔值的单元素关联数组创建一个新的关联数组

[英]Create a new associative array from a single-element associative array containing related comma-separated values

I am trying to create a new array structure from a single-element associative array where the key and the value are both comma-separated strings with related data.我正在尝试从一个单元素关联数组创建一个新的数组结构,其中键和值都是带有相关数据的逗号分隔字符串。

Which array function should I use to do this?我应该使用哪个数组 function 来执行此操作?

Input array:输入数组:

[
  "id,zip,state,city,county,territory,price" => "1,90001,CA,Los Angeles,Los Angeles,Orange CA,40"
]

Desired output:所需的 output:

[
    "id" => 1,
    "zip" => 90001,
    "state" => "CA",
    "city" => "Los Angeles",
    "county" => "Los Angeles",
    "territory" => "Orange CA",
    "price" => 40
]

"id,zip,state,city,county,territory,price" is one key, not multiple. "id,zip,state,city,county,territory,price"是一个键,不是多个键。 So you have to split them.所以你必须把它们分开。

$old = ["id,zip,state,city,county,territory,price" => "1,90001,CA,Los Angeles,Los Angeles,Orange CA,40"];

$keys = explode(',', $key = array_key_first($old));
$values = explode(',', $old[$key]);
$new = array_combine($keys, $values);

Gives

array(7) {
  ["id"]=>
  string(1) "1"
  ["zip"]=>
  string(5) "90001"
  ["state"]=>
  string(2) "CA"
  ["city"]=>
  string(11) "Los Angeles"
  ["county"]=>
  string(11) "Los Angeles"
  ["territory"]=>
  string(9) "Orange CA"
  ["price"]=>
  string(2) "40"
}

Almost identical to @Markus's, but key() can be used in more php versions.几乎与@Markus 相同,但key()可用于更多 php 版本。

Code: ( Demo )代码:(演示

$array = [
    "id,zip,state,city,county,territory,price" => "1,90001,CA,Los Angeles,Los Angeles,Orange CA,40"
];

$key = key($array);
var_export(
    array_combine(
        explode(',', $key),
        explode(',', $array[$key])
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM