[英]How to convert an array into key-value pair array?
I am having this array : 我有这个数组:
array(
0 => array("name", "address", "city"),
1=> array( "anoop", "palasis", "Indore"),
2=> array( "ravinder", "annapurna", "Indore")
)
and i want to make this array in this way : 我想以这种方式制作此数组:
array(
0 => array("name" = >"anoop" , "address" = >"palasia", "city" = >"Indore"),
1 => array("name" = >"ravinder" , "address" = >"annapurna", "city" = >"Indore")
)
Use array_combine . 使用array_combine 。 If
$array
contains your data 如果
$array
包含您的数据
$result = array(
array_combine($array[0], $array[1]),
array_combine($array[0], $array[2])
);
In general 一般来说
$result = array();
$len = count($array);
for($i=1;$i<$len; $i++){
$result[] = array_combine($array[0], $array[$i]);
}
The modern way is: 现代方式是:
$data = array_column($data, 'value', 'key');
In your case: 在您的情况下:
$data = array_column($data, 1, 0);
If your data are in $array
: 如果您的数据在
$array
:
$res = array();
foreach ($array as $key=>$value) {
if ($key == 0) {
continue;
}
for ($i = 0; $i < count($array[0]); $i++) {
$res[$array[0][$i]] = $value[$i];
}
}
The result is now in $res
. 现在的结果是
$res
。
Here is a function that you can use: 您可以使用以下功能:
function rewrap(Array $input){
$key_names = array_shift($input);
$output = Array();
foreach($input as $index => $inner_array){
$output[] = array_combine($key_names,$inner_array);
}
return $output;
}
Here is a demonstration: 这是一个示范:
// Include the function from above here
$start = array(
0 => array("name", "address", "city"),
1 => array("anoop", "palasis", "Indore"),
2 => array("ravinder", "annapurna", "Indore")
);
print_r(rewrap($start));
This outputs: 输出:
Array
(
[0] => Array
(
[name] => anoop
[address] => palasis
[city] => Indore
)
[1] => Array
(
[name] => ravinder
[address] => annapurna
[city] => Indore
)
)
Note: Your first array defined index 1
twice, so I changed the second one to 2
, like this: 注意:您的第一个数组两次定义了索引
1
,所以我将第二个更改为2
,如下所示:
array(0 => array("name", "address", "city"), 1 => array("anoop", "palasis", "Indore"),2 => array("ravinder", "annapurna", "Indore"))
That was probably just a typo. 那可能只是一个错字。
Assuming that you are parsing a CSV file, check out the answers to this question: 假设您正在解析CSV文件,请查看此问题的答案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.