我试图使用mysql查询的结果创建一个数组,但我正在创建一个对象数组。
尝试将对象数组转换为数组失败,这是最好的方法吗?
echo json_decode(json_encode($iconsArray), true); // didnt work
这是我的查询
function listIcons(){
global $link;
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
$iconsArray[] = $row;
}
$allIcons = json_encode($iconsArray);
echo $allIcons;
return array($allIcons);
}
allIcons outout是
$allIcons = [
0:{icon_1: "01_a", icon_2: "01_b", icon_3: "01_c", icon_4: "01_d"}
1{icon_1: "02_a", icon_2: "02_b", icon_3: "02_c", icon_4: "02_d"}
]
我需要但不能实现的输出
$allIcons = [
0:"01_a"
1:"02_a"
2:"01_b"
3:"02_b"
4:"03_a"
5:"02_b"
...
]
答案 0 :(得分:1)
这很可能是最容易做到的事情:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
foreach ($row as $icon) {
$icons[] = $icon;
}
}
var_dump($icons);
没有额外循环的替代方案就是这样:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
$icons = [];
while ($row = mysqli_fetch_assoc($resultqueryAssets)) {
$icons = array_merge($icons, array_values($row));
}
var_dump($icons);
实际上,如果你根本不取一个关联数组,事情会变得更容易:
<?php
// ....
$queryAssets = "SELECT DISTINCT icon_1,icon_2,icon_3,icon_4 FROM icons";
$resultqueryAssets = mysqli_query($link, $queryAssets) or
die(mysqli_error($link));
$icons = [];
while ($row = mysqli_fetch_row($resultqueryAssets)) {
$icons = array_merge($icons, $row);
}
var_dump($icons);
我没有运行这些代码片段,只是输入了它们。我希望他们中没有愚蠢的错字......