是否可以使用递增的数字填充数组?例如
$myArr = ["red", "green", "blue"];
$type = "colour";
我想以某种方式合并这些并添加排序顺序,所以我最终得到以下
Array
(
[red] => Array
(
[type] => "colour"
[sort] => 1
)
[green] => Array
(
[type] => "colour"
[sort] => 2
)
[blue] => Array
(
[type] => "colour"
[sort] => 3
)
)
到目前为止,我只管理过:
$additional_data = array_pad([], count($myArr), ['type_id' => $type_id]);
$data = array_combine($myArr, $additional_data);
正在屈服:
Array
(
[red] => Array
(
[type] => "colour"
)
[green] => Array
(
[type] => "colour"
)
[blue] => Array
(
[type] => "colour"
)
)
我知道我可以通过迭代颜色来做到这一点,但想知道是否可以在没有循环的情况下完成。
由于
答案 0 :(得分:1)
我这样做了,希望可以帮忙
$myArr = ["red", "green", "blue"];
$type = "colour";
$x = array();
for($i=0;$i<count($myArr);$i++){
$x[$myArr[$i]]=array();
$x[$myArr[$i]]["type"]=$type;
$x[$myArr[$i]]["sort"]=$i;
}
var_dump($x);
答案 1 :(得分:1)
您为解决此问题而发布的版本始终将1作为sort_order。
const cursor = db.collection('name').aggregate(
[
{
"$match": {code: 10}
},
{
"$count": "count"
}
],
{
"allowDiskUse": false
}
)
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
console.log('aggregate:', doc.count);
}
...输出
$myArr = ["red", "green", "blue"];
$type_id = "colour";
$sort = 0;
$additional_data = array_pad([], count($myArr), ['type_id' => $type_id, 'sort_order' => ++$sort]);
$data = array_combine($myArr, $additional_data);
print_r($data);
然后,您可以使用array_walk处理结果以更正值...
Array
(
[red] => Array
(
[type_id] => colour
[sort_order] => 1
)
[green] => Array
(
[type_id] => colour
[sort_order] => 1
)
[blue] => Array
(
[type_id] => colour
[sort_order] => 1
)
)
它纠正了它。
$myArr = ["red", "green", "blue"];
$type_id = "colour";
$sort = 0;
$additional_data = array_pad([], count($myArr), ['type_id' => $type_id, 'sort_order' => ++$sort]);
$data = array_combine($myArr, $additional_data);
$sort = 1;
array_walk($data, function (&$item, $key) use(&$sort) {
$item['sort_order'] = $sort++;
});
print_r($data);
答案 2 :(得分:0)
我明白了。非常简单。
$myArr = ["red", "green", "blue"];
$type = "colour";
$sort = 0;
$additional_data = array_pad([], count($myArr), ['type_id' => $type_id, 'sort_order' => ++$sort]);
$data = array_combine($myArr, $additional_data);