我有这个代码,但是如何在数组中添加额外的项目?在这个例子中,我想添加一个带有'slug'标题的数组。 这不起作用。
$interviewresult = $db->query($interviewsql);
$interviewdata = $interviewresult->fetch_assoc();
$interviewdata['slug'] = $slug->create($interviewdata['title']);
while($interviewtrackerlist = $interviewresult->fetch_assoc()) {
$interviewtracker_list[] = $interviewdata;
}
echo "<pre>".print_r($interviewtracker_list,1)."</pre>";
这会重复一个项目:
Array
(
[0] => Array
(
[id] => 4041
[title] => Interview: Blaat.nl
[date_posted] => 2014-05-01 10:13:09
[wanneer] => 01-05
[slug] => interview-blaat-nl
)
[1] => Array
(
[id] => 4041
[title] => Interview: Blaat.nl
[date_posted] => 2014-05-01 10:13:09
[wanneer] => 01-05
[slug] => interview-blaat-nl
)
[2] => Array
(
[id] => 4041
[title] => Interview: Blaat.nl
[date_posted] => 2014-05-01 10:13:09
[wanneer] => 01-05
[slug] => interview-blaat-nl
)
)
但我希望有这样一个数组:
Array
(
[0] => Array
(
[id] => 4041
[title] => Interview: Blaat.nl
[date_posted] => 2016-05-01 10:13:09
[wanneer] => 01-05
[slug] => interview-blaat-nl
)
[1] => Array
(
[id] => 4042
[title] => Interview: Yaddah Yaddah
[date_posted] => 2016-05-10 22:53:49
[wanneer] => 01-05
[slug] => interview-yaddah-yaddah
)
[2] => Array
(
[id] => 4043
[title] => Interview: Pete Puck
[date_posted] => 2016-10-07 21:13:08
[wanneer] => 01-05
[slug] => interview-pete-puck
)
)
我该怎么做?
答案 0 :(得分:0)
查看while
循环中的这一行,
$interviewtracker_list[] = $interviewdata;
^ look here
在循环的每次迭代中,您将相同的数据推送到数组。你的代码应该是这样的:
$interviewresult = $db->query($interviewsql);
$interviewtracker_list = array();
while($interviewdata = $interviewresult->fetch_assoc()){
$interviewdata['slug'] = $slug->create($interviewdata['title']);
$interviewtracker_list[] = $interviewdata;
}
// display $interviewtracker_list array
var_dump($interviewtracker_list);
答案 1 :(得分:0)
简单。
获取结果,迭代它,并在循环内更改或添加字段:
$interviewresult = $db->query($interviewsql);
while($interviewdata = $interviewresult->fetch_assoc()) {
$interviewdata['slug'] = $slug->create($interviewdata['title']);
$interviewtracker_list[] = $interviewdata;
}