【问题标题】:foreach access the index or an associative arrayforeach 访问索引或关联数组
【发布时间】:2010-09-09 06:36:21
【问题描述】:

我有以下代码sn-p。

$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";

$index = 0;
foreach($items as $key => $value)
{
    echo "$index is a $key containing $value\n";
    $index++;
}

预期输出:

0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test

有没有办法省略$index 变量?

【问题讨论】:

    标签: php foreach


    【解决方案1】:

    你的 $index 变量有点误导。该数字不是索引,您的“A”、“B”、“C”、“D”键是。您仍然可以通过编号索引 $index[1] 访问数据,但这并不是重点。如果您真的想保留编号索引,我几乎会重组数据:

    $items[] = array("A", "Test"); $items[] = array("B", "Test"); $items[] = array("C", "Test"); $items[] = array("D", "Test"); foreach($items as $key => $value) { 回声$键。是一个'.$value[0]。'包含 '.$value[1]; }

    【讨论】:

    • 其实就是索引,A、B、C、D是数组键。
    • 但是您对数据重组的看法是正确的,您的示例几乎就是我最终得到的。 :)
    【解决方案2】:

    你可以这样做:

    $items[A] = "Test";
    $items[B] = "Test";
    $items[C] = "Test";
    $items[D] = "Test";
    
    for($i=0;$i<count($items);$i++)
    {
        list($key,$value) = each($items[$i]);
        echo "$i $key contains $value";
    }
    

    我以前没有这样做过,但理论上它应该可以工作。

    【讨论】:

    【解决方案3】:

    请注意您在此处定义密钥的方式。虽然您的示例有效,但它可能并不总是:

    $myArr = array();
    $myArr[A] = "a";  // "A" is assumed.
    echo $myArr['A']; // "a" - this is expected.
    
    define ('A', 'aye');
    
    $myArr2 = array();
    $myArr2[A] = "a"; // A is a constant
    
    echo $myArr['A']; // error, no key.
    print_r($myArr);
    
    // Array
    // (
    //     [aye] => a
    // )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多