设置变量等于索引计数

时间:2017-01-31 04:36:22

标签: php arrays

我有一个数组

$ ID =数组(0 =>" 12",1 =>" 14 = 2>" 27",3 =>&# 34; 987",4 =>" 23");

然后我有这个功能:

foreach ($doodads AS $doodad) {
    if ($page == 1) {
        $doodad['row'] = $X;
    } else {
        $doodad['row'] = count($all_ids) + $X;
    }

    $return[] = Doodads_Model_Ajax::formatCallbackDoodad($doodad);
}

如何将$X设置为数组$ ID(0,1,2,3或4)中当前索引的编号?

1 个答案:

答案 0 :(得分:1)

使用foreach获取键和值而不仅仅是值。

foreach($doodads as $key => $doodad) {
    echo 'Key: ', $key, "\n";
    print_r($doodad);
}

在你的情况下,$ key将是$ X;

foreach($doodads as $X => $doodad)

要在for循环中计数,请尝试此操作。

$x = 0;
foreach($doodads as $key => $doodad) {
    echo 'Key: ', $key, "\n";
    echo 'X: ', $x, "\n\n";
    ++$x; // Add one to x.
}