我有点新,可以用指针或两个......
所以下面的代码显示了这个:
Bill: eats: 0.5, drinks: 0.
John: eats: 0, drinks: 0.
Joe: eats: 0, drinks: 0.
了解账单如何吃 0.5 ...... 如果账单或其他任何人“吃”超过0 我希望它们从数组中删除。我试图使用未设置,但我不确定我是否正确使用它。
我所期待的是John和Joe如下所示,因为账单吃了一些并被删除了..
John: eats: 0, drinks: 0.
Joe: eats: 0, drinks: 0.
all done eating.
我做错了什么,是 if($ value> 0)未设置的行?
<?php
$addresses = array
(
array("Bill",0.5,0),
array("John",0,0),
array("Joe",0,0)
);
echo $addresses[0][0].": eats: ".$addresses[0][1].", drinks: ".$addresses[0][2].".<br>";
echo $addresses[1][0].": eats: ".$addresses[1][1].", drinks: ".$addresses[1][2].".<br>";
echo $addresses[2][0].": eats: ".$addresses[2][1].", drinks: ".$addresses[2][2].".<br>";
foreach ($addresses as $key => $value)
{
if ($value > 0) unset($key[$value]);
}
if ($var == 0) echo 'all done eating.';
?>
答案 0 :(得分:1)
迭代二维数组。
因此,这意味着$value
实际上是一个数组。
条件是:
if($value[1] > 0)//1st element is eats, zero: name, 2: drinks
或完整修改:
<?php
$addresses = array (
array("Bill",0.5,0),
array("John",0,0),
array("Joe",0,0)
);
echo $addresses[0][0].": eats: ".$addresses[0][1].", drinks: ".$addresses[0][2].".<br>";
echo $addresses[1][0].": eats: ".$addresses[1][1].", drinks: ".$addresses[1][2].".<br>";
echo $addresses[2][0].": eats: ".$addresses[2][1].", drinks: ".$addresses[2][2].".<br>";
foreach ($addresses as $key => $value) {
if ($value[1] > 0) {unset($addresses[$key]); echo("removed ".$value[0]."<br>");}
}
if ($var == 0) echo 'all done eating.';
?>
我添加了echo
语句,以便检查核心性。
答案 1 :(得分:0)
$ value是一个数组。尝试使用
if ($value[1] > 0) unset($addresses[$key]);
顺便说一下,您应该尝试使用字符串键来考虑数组。它应该很好看,很容易看到。
例如:
$eaters = array(
0 => array(
'name' => 'John',
'eats' => 0,
'drinks' => 0
),
1 => array(
'name' => 'Joseph',
'eats' => 0.5,
'drinks' => 0
)
)
然后:
echo $eaters[0]['name']; // outputs John.
附加说明:
在foreach循环中取消设置元素有时可能很危险。你必须非常小心,不要取消尚未解决的问题。另一种方法是记住在另一个临时数组中删除的内容,并在另一个循环中取消设置。
祝你好运
答案 2 :(得分:0)
快速回复:
<?php
// ...
foreach ($addresses as $key => $value) {
if ($value[1] > 0) {
// you have to unset the entry in $addresses
unset($addresses[$key]);
}
}
// ...
?>
:)