[英]Having difficulties with php foreach and passing by reference
I'm pulling some data from a database (with a function I have called query), and I want to add another key/value pair to each result, ie: 我从数据库中提取一些数据(使用我称之为查询的函数),我想为每个结果添加另一个键/值对,即:
$items = query("SELECT * FROM items");
foreach($items as &$item) {
$item['fixedname'] = str_replace(' ','_',$item['name']);
}
Now I want to put these on an html view, ie: 现在我想把它们放在一个html视图上,即:
<?php foreach($items as $item): ?>
<div id="<?= $item['fixedname'] ?>" ><?= $item['name'] ?></div>
<?php endforeach; ?>
However, this doesn't output correctly. 但是,这不能正确输出。 For instance, when the query returns two items, the loop in the php outputs the same thing twice.
例如,当查询返回两个项时,php中的循环输出两次相同的东西。 If there are three: it outputs the first one, then two of the second one.
如果有三个:它输出第一个,然后输出第二个中的两个。 What's the problem here?
这有什么问题?
When modifying using foreach() I've had weird results on occasion. 使用foreach()进行修改时,我偶尔会得到奇怪的结果。 I use
我用
foreach ($items as $key=>$value) {
$items[$key] = modified($value);
}
Or, why not do it in the SQL SELECT your, fields, here, REPLACE(name, ' ', '-') AS fixedname
或者,为什么不在SQL
SELECT your, fields, here, REPLACE(name, ' ', '-') AS fixedname
You could do a normal for loop 你可以做一个正常的循环
<?php
for($i=0; $i < count($items); $i++){
$items[$i]['fixedname'] = str_replace(' ','_',$items[$i]['name']);
}
?>
Then everything will be ready when you go to your next foreach. 当你去下一个foreach时,一切都会准备就绪。
The data returned on the right side of the foreach is a copy of the data, it can't be modified directly. foreach右侧返回的数据是数据的副本,不能直接修改。 Instead you need to fetch both the $key (the ID of the item in the array) and the $item.
相反,您需要同时获取$ key(数组中项目的ID)和$ item。 By letting PHP telling you the $key you don't need to worry about whether the array is normal (eg having indexes of 0,1,2,...) and associative.
通过让PHP告诉你$ key你不需要担心数组是否正常(例如索引为0,1,2,......)和关联。
This example would walk the $items array and add 'fixedname' into it.
foreach($items as $key => $item) {
$items[$key]['fixedname'] = str_replace(' ','_',$item['name']);
}
u have bunch of wrong things 你有一堆错误的东西
1 - dont use mysql , use PDO
or mysqli
instead 1 - 不要使用mysql,而是使用
PDO
或mysqli
2 - $items = query("SELECT * ....
--->Call to undefined function query() 2 -
$items = query("SELECT * ....
--->调用未定义的函数查询()
change it to 改为
$items = mysql_query("SELECT * ....
3 - Invalid argument supplied for foreach()
, 3 -
Invalid argument supplied for foreach()
,
you missed to fetch your query 你错过了获取你的查询
try this whole code 试试这整个代码
$items = mysql_query("SELECT * FROM items");
?>
<?php while ($row = mysql_fetch_array($items) ) {?>
<div id="<?php echo $row['fixedname'] ;?>" ><?php echo $row['name']; ?></div>
<?php } ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.