PHP foreach循环只做一次而不是多次
我正在为整个脚本运行一个foreach循环,它检查了9项内容 假设其中五个值为“a”,四个值为“b” 如何编写只返回“a”和“b”一次的IF条件(或其他条件)?简单方法(检查最后一个值) 使用一个存储先前内容的变量,并将其与当前迭代进行比较(仅当类似项是连续的时才有效) 更稳健的方法(将使用过的值存储在数组中) 或者,如果您有复杂的对象,需要检查内部属性和类似的内容,而这些内容不是连续的,请将使用的对象存储到数组中:PHP foreach循环只做一次而不是多次,php,curl,Php,Curl,我正在为整个脚本运行一个foreach循环,它检查了9项内容 假设其中五个值为“a”,四个值为“b” 如何编写只返回“a”和“b”一次的IF条件(或其他条件)?简单方法(检查最后一个值) 使用一个存储先前内容的变量,并将其与当前迭代进行比较(仅当类似项是连续的时才有效) 更稳健的方法(将使用过的值存储在数组中) 或者,如果您有复杂的对象,需要检查内部属性和类似的内容,而这些内容不是连续的,请将使用的对象存储到数组中: $used = array(); foreach ($things as $t
$used = array();
foreach ($things as $thing) {
// Check if it has already been used (exists in the $used array)
if (!in_array($thing, $used)) {
// do the thing
// and add it to the $used array
$used[] = $thing;
}
}
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)
例如(1):
例如(2)
您是否可以更具体一些(插入包含“内容”对象的代码片段可能会有所帮助) 听起来,您正在尝试获取数组的唯一值:
$used = array();
foreach ($things as $thing) {
// Check if it has already been used (exists in the $used array)
if (!in_array($thing, $used)) {
// do the thing
// and add it to the $used array
$used[] = $thing;
}
}
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)