当数组有非数字键时,使用 array_splice() 输入空值
Use array_splice() to enter empty values when the array has non-numeric keys
我查看了 this question,但我似乎无法让代码为我的目的工作。
我有一个结构如下的数组 ($array
),其中充满了来自数据库的数据:
array(369) {
array(3) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["description"] => string(n) "..."
}
array(3) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["description"] => string(n) "..."
}
...
}
但是,此数组数据将创建一个 CSV,我还需要插入空列。因此我需要数组最终看起来像这样:
array(369) {
array(5) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
array(5) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
...
}
我试过使用 array_splice()
在相关点输入空白值:
array_splice($array, 2, 0, "");
array_splice($array, 4, 0, "");
但这最终只是破坏了数组,后来使用 fputcsv()
的代码甚至没有将它 识别为 数组。如何输入这些空白值?
foreach ($array as $value) {
fputcsv($fp, $value);
}
请注意: 数组 key
被标记为什么并不重要。它可以像上面建议的那样,空白,数字,零...重要的是我需要一个空白 value
.
$array = array_map(function (array $row) {
static $default = [
'id' => null,
'title' => null,
'title2' => null,
'description' => null,
'description2' => null
];
return array_merge($default, $row);
}, $array);
array_merge
保留第一个数组的结构(键和顺序),但替换其键与第二个数组匹配的任何值。
我查看了 this question,但我似乎无法让代码为我的目的工作。
我有一个结构如下的数组 ($array
),其中充满了来自数据库的数据:
array(369) {
array(3) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["description"] => string(n) "..."
}
array(3) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["description"] => string(n) "..."
}
...
}
但是,此数组数据将创建一个 CSV,我还需要插入空列。因此我需要数组最终看起来像这样:
array(369) {
array(5) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
array(5) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
...
}
我试过使用 array_splice()
在相关点输入空白值:
array_splice($array, 2, 0, "");
array_splice($array, 4, 0, "");
但这最终只是破坏了数组,后来使用 fputcsv()
的代码甚至没有将它 识别为 数组。如何输入这些空白值?
foreach ($array as $value) {
fputcsv($fp, $value);
}
请注意: 数组 key
被标记为什么并不重要。它可以像上面建议的那样,空白,数字,零...重要的是我需要一个空白 value
.
$array = array_map(function (array $row) {
static $default = [
'id' => null,
'title' => null,
'title2' => null,
'description' => null,
'description2' => null
];
return array_merge($default, $row);
}, $array);
array_merge
保留第一个数组的结构(键和顺序),但替换其键与第二个数组匹配的任何值。