Php 如何从for each循环中获取值
我有以下功能:Php 如何从for each循环中获取值,php,Php,我有以下功能: public function get_contents() { $items = array(); foreach($this->items as $tmpItem) { $item = null; $item['id'] = $tmpItem; $item['name'] = $this->names[$tmpItem]; $item['price'] =
public function get_contents() {
$items = array();
foreach($this->items as $tmpItem) {
$item = null;
$item['id'] = $tmpItem;
$item['name'] = $this->names[$tmpItem];
$item['price'] = $this->prices[$tmpItem];
$item['qty'] = $this->qtys[$tmpItem];
$item['X'] = $this->X$tmpItem];
$items[] = $item;
}
return $items;
}
我想得到X的值。
因此,如果有3个循环,例如X的值为no,no,yes,那么我将如何使用这些值
我试过以下方法
public function update_X($X){
foreach($this->items as $item) {
if(strstr($this->Xs[$item], 'no') ==!false){
$this->Xs = 'no';
$item['X'] = $this->Xs;
}
else
$this->Xs = 'yes';
$item['X'] = $this->Xs;
}
}
它将只使用添加的X的最后一个值。因此,在这种情况下,它将是“是”。如果X的值为no,那么我想要的是$item['X']的值为no
欢迎任何帮助您总是重置Xs,而不是连接。这就是为什么你总是只得到最后一个值 试试这个:
$Xs="";
foreach($this->items as $item) {
$Xs.=$this->X[$item];
}
// $Xs is now "nonoyes"
请尽量用更能理解的方式表达你的问题。显示输入和预期输出的示例。第一个示例显示如何使用for循环外部的数组存储多个结果。在第二个例子中,你为什么不能这样做呢。或者,您可以尝试使用yield函数从循环中的函数返回多个项。@kainaw如果我只检索X和print的所有值,则类似于$X=no。不,是,那太好了。我只是不知道怎么去。此时,它只显示最后一个值,即“$X=”yes“,非常感谢您的帮助。对不起,我还没有机会回复。