我有以下数组:
$all_items = Array
(
[0] => abc
[1] => bcd
[2] => cde
[3] => def
[4] => efg
)
我想将此数组转换为如下所示的关联数组。
array(
array('A'=>abc, 'position'=>0),
array('A'=>bcd, 'position'=>1),
array('A'=>cde, 'position'=>2),
array('A'=>abc, 'position'=>3),
array('A'=>bcd, 'position'=>4)
),
到目前为止,我尝试了许多不同的方法,没有运气。这是我的代码。
$k = 0;
foreach($all_items as $item) {
$all_items[$key]['src'] =$item;
$all_items[$key]['position']=i;
$k++;
};
我错过了什么?
答案 0 :(得分:4)
这应该非常简单,试试这样:
<?php
$items = array();
foreach($all_items as $k=>$v) {
$items[] = array(
'A' => $v,
'position' => $k
);
}
答案 1 :(得分:3)
这应该适合你:
(这里我只是用array_map()
遍历数组并为每个值返回一个新数组)
<?php
$all_items = ["abc", "bcd", "cde", "def", "efg"];
$result = array_map(function($v, $k){
return ["A" => $v, "position" => $k];
}, $all_items, array_keys($all_items));
print_r($result);
?>
输出:
Array
(
[0] => Array
(
[A] => abc
[position] => 0
)
//...
[4] => Array
(
[A] => efg
[position] => 4
)
)
答案 2 :(得分:1)
尝试 -
$newArr = array_map('buildArr', $all_items, array_keys($all_items));
function buildArr($data, $key) {
$result = array('A' => $data, 'position' => $key);
return $result;
}
var_dump($newArr);