php: foreach() 如何分配给两个变量

发布于 2025-01-06 07:31:25 字数 1465 浏览 0 评论 0原文

function example()
{

    foreach ($choices as $key => $choice) {       # \__ both should run parallel
    foreach ($vtitles as $keystwo => $vtitle) {   # /

        $options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected  
.'>'. check_plain($choice) .'</option>';


    } // end of vtitle    
    } // end of choice

    return $options;
}

回答以下一些问题以及我想要实现的目标。

  1. 数组$choices没有数字索引。
  2. 数组 $vtitle 按数字索引。
  3. 它们不会比彼此短,因为我有代码会在该代码运行之前处理这个问题。
  4. 我正在尝试返回 $options 变量。问题是 $choices[0]$vtitle[0] 只能使用一次。希望我能够表达我的问题。
  5. 我不想为 $choices 中的每个值都遍历一次 $vtitles 数组。

@hakre:谢谢,在你的帮助下我几乎解决了这个问题。

我收到变量 $vtitle 的错误:

InvalidArgumentException: Passed variable is not an array or object, using empty array    
instead in ArrayIterator->__construct() (line 35 of /home/vishal/Dropbox/sites/chatter/sites
/all/themes/kt_vusers/template.php).

我确信它是一个数组,这是使用 print_r 的输出

Array ( [0] => vishalkh [1] => newandold ) 

可能出了什么问题?

以下对我有用,谢谢 hakre

while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
function example()
{

    foreach ($choices as $key => $choice) {       # \__ both should run parallel
    foreach ($vtitles as $keystwo => $vtitle) {   # /

        $options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected  
.'>'. check_plain($choice) .'</option>';


    } // end of vtitle    
    } // end of choice

    return $options;
}

Answers to some of the below questions and what I am trying to achieve.

  1. Array $choices is not numerically indexed.
  2. Array $vtitle is numerically indexed.
  3. They won't be shorter than each other as I have code which will take care of this before this code runs.
  4. I am trying to return $options variable. The issue is that $choices[0] and $vtitle[0] should be used only once. Hope I was able to express my problem.
  5. I do not want to go through the $vtitles array once for each value in $choices.

@hakre: thanks I have nearly solved it with your help.

I am getting an error for variable $vtitle:

InvalidArgumentException: Passed variable is not an array or object, using empty array    
instead in ArrayIterator->__construct() (line 35 of /home/vishal/Dropbox/sites/chatter/sites
/all/themes/kt_vusers/template.php).

I am sure its an array this is the output using print_r

Array ( [0] => vishalkh [1] => newandold ) 

What might be going wrong ?

The below worked for me , thank you hakre

while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

走走停停 2025-01-13 07:31:25

它不会按照您用伪代码概述的方式工作。然而,SPL 提供了一种同时迭代多个迭代器的方法。它称为 MultipleIterator,您可以根据需要附加任意多个迭代器:

$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($array1));
$multi->attachIterator(new ArrayIterator($array2));

foreach($multi as $value)
{
    list($key1, $key2) = $multi->key();
    list($value1, $value2) = $value;
}

请参阅操作: 演示

编辑: 第一个示例显示了来自声压级。它的好处是它可以处理任何类型的迭代器,而不仅仅是数组。如果你想用数组表达类似的东西,你可以用经典的 while(list()=each()) 循环来实现类似的东西,它允许比 foreach 更多的表达式。

while
(
    (list($key1, $value1) = each($array1))
    && (list($key2, $value2) = each($array2))
)
{
    printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}

演示(迭代最小数量的元素)


另请参阅相关问题:PHP foreach 循环中的多个索引变量

It does not work the way you outline with your pseudo code. However, the SPL offers a way to iterate multiple iterators at once. It's called MultipleIterator and you can attach as many iterators as you like:

$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($array1));
$multi->attachIterator(new ArrayIterator($array2));

foreach($multi as $value)
{
    list($key1, $key2) = $multi->key();
    list($value1, $value2) = $value;
}

See it in action: Demo

Edit: The first example shows a suggestion from the SPL. It has the benefit that it can deal with any kind of iterators, not only arrays. If you want to express something similar with arrays, you can achieve something similar with the classic while(list()=each()) loop, which allows more expressions than foreach.

while
(
    (list($key1, $value1) = each($array1))
    && (list($key2, $value2) = each($array2))
)
{
    printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}

Demo (the minimum number of elements are iterated)


See as well a related question: Multiple index variables in PHP foreach loop

倒数 2025-01-13 07:31:25

一般情况下,你不能在 foreach 循环中执行此操作。但你可以在 PHP5 中这样做:

$obj1 = new ArrayObject($arr1);
$it1 = $obj1->getIterator();

$obj2 = new ArrayObject($arr2);
$it2 = $obj2->getIterator();

while( $it1->valid() && $it2->valid())
{
    echo $it1->key() . "=" . $it1->current() . "\n";
    $it1->next();

    echo $it2->key() . "=" . $it2->current() . "\n";
    $it2->next();    
}

在旧版本的 PHP 中,它会像这样:

while (($choice = current($choices)) && ($vtitle = current($vtitles))) {       
    $key_choice = key($choices);
    $key_vtitle = key($vtitles);
    next($choices);
    next($vtitles);
}

you can't do it in foreach loop in general case. But you can do it like this in PHP5:

$obj1 = new ArrayObject($arr1);
$it1 = $obj1->getIterator();

$obj2 = new ArrayObject($arr2);
$it2 = $obj2->getIterator();

while( $it1->valid() && $it2->valid())
{
    echo $it1->key() . "=" . $it1->current() . "\n";
    $it1->next();

    echo $it2->key() . "=" . $it2->current() . "\n";
    $it2->next();    
}

In older versions of PHP it will be like this:

while (($choice = current($choices)) && ($vtitle = current($vtitles))) {       
    $key_choice = key($choices);
    $key_vtitle = key($vtitles);
    next($choices);
    next($vtitles);
}
羁绊已千年 2025-01-13 07:31:25

简短的回答,不。

你可以做的是:

foreach ($array1 as $k => $v)
    performMyLogic($k, $v);

foreach ($array2 as $k => $v)
    performMyLogic($k, $v);

Short Answer, no.

What you can do instead is:

foreach ($array1 as $k => $v)
    performMyLogic($k, $v);

foreach ($array2 as $k => $v)
    performMyLogic($k, $v);
天涯离梦残月幽梦 2025-01-13 07:31:25

如果密钥相同,您可以这样做:

foreach ($choices as $key => $choice) {
    $vtitle = $vtitles[$key];
}

If the keys are the same, you can do this:

foreach ($choices as $key => $choice) {
    $vtitle = $vtitles[$key];
}
等待我真够勒 2025-01-13 07:31:25

你可能必须重新调整你的逻辑才能做你想做的事。有什么理由不能只使用 2 个 foreach 循环吗?或者将其中一个嵌套在另一个中?

编辑:正如其他人指出的那样,如果 PHP 确实支持您想要做的事情,那么它根本不安全..所以它不支持可能是一件好事:)

You may have to refigure your logic to do what you want. Any reason you can't just use 2 foreach loops? Or nest one inside the other?

EDIT: as others have pointed out, if PHP did support what you're trying to do, it wouldn't be safe at all.. so it's probably a good thing that it doesn't :)

单身情人 2025-01-13 07:31:25

也许您想要这个:

//get theirs keys
$keys_choices = array_keys($choices);
$keys_vtitles = array_keys($vtitles);

//the same size I guess
if (count($keys_choices) === count($keys_vtitles)) {

    for ($i = 0;$i < count($keys_choices); $i++) {

        //First array
        $key_1 = $keys_choices[$i];
        $value_1 = $choices[$keys_choices[$i]];

        //second_array
        $key_2 = $key_vtitles[$i];
        $value_2 = $vtitles[$keys_vtitles[$i]];

        //and you can operate
    }
}

但是如果大小相同,这就会起作用。但您可以更改此代码。

Maybe you want this:

//get theirs keys
$keys_choices = array_keys($choices);
$keys_vtitles = array_keys($vtitles);

//the same size I guess
if (count($keys_choices) === count($keys_vtitles)) {

    for ($i = 0;$i < count($keys_choices); $i++) {

        //First array
        $key_1 = $keys_choices[$i];
        $value_1 = $choices[$keys_choices[$i]];

        //second_array
        $key_2 = $key_vtitles[$i];
        $value_2 = $vtitles[$keys_vtitles[$i]];

        //and you can operate
    }
}

But this will work if size is the same. But you can change this code.

枫林﹌晚霞¤ 2025-01-13 07:31:25

您需要使用两个 foreach 循环。

foreach ($choices as $keyChoice => $choice)
{
    foreach ($vtitles as $keyVtitle => $vtitle)
    {
        //Code to work on values here
    }
}

You need to use two foreach loops.

foreach ($choices as $keyChoice => $choice)
{
    foreach ($vtitles as $keyVtitle => $vtitle)
    {
        //Code to work on values here
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文