array( array(-6ren">
gpt4 book ai didi

php - Mysql 结果存入数组(PHP)

转载 作者:行者123 更新时间:2023-12-02 06:44:09 25 4
gpt4 key购买 nike

如何将 mysql 结果(来自 mysql_fetch_array)转换成这样的形式?

$some = array(
"comments" => array(
array( "text" => "hi", "id" => "1" ),
array( "text" => "hi", "id" => "2" ),
array( "text" => "hi", "id" => "3" ),
array( "text" => "hi", "id" => "4" )
)
);

虽然数据库看起来像:

评论

id  text
1 blabla bla
2 bla bla

我尝试用 foreach/while 获取值并将其插入到两个数组中,但没有成功...

$some = array(
"comments" => array()
);

$q = $mysql->sf('*', TBL_QST);
foreach($mysql->fetch($q) as $row) {
$some[] = $row;
// $some["comments"][] = $row;
}

最佳答案

我的 print_r 给出:

Array
(
[comments] => Array
(
[0] => Array
(
[text] => lorem ipsum
[id] => 0
)
[1] => Array
(
[text] => lorem ipsum
[id] => 1
)
[2] => Array
(
[text] => lorem ipsum
[id] => 2
)
)
)

我为它做的 php 是:

$comments = array(
'comments' => array()
);

/* To simualate the loop */
for ($i = 0; $i < 3; $i++) {
array_push($comments['comments'], array(
'text' => 'lorem ipsum',
'id' => $i
)
);
}

希望这对您有所帮助,并且我没有误解您的问题。

关于php - Mysql 结果存入数组(PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2984005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com