PHP - 查找数组元素是奇数还是偶数

时间:2015-08-17 12:09:19

标签: php arrays associative-array

我有一系列这样的项目:

$data = array(
            'item1' => array( // is even
                'icon' => 'commenting',
                'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
            ), 
            'item2' => array(// is odd
                'icon' => 'sticky-note',
                'content' => 'Debitis id eligendi assumenda, cumque optio veniam eos perferendis molestias explicabo odit',
            ),
            'item3' => array(// is even
                'icon' => 'users',
                'content' => 'Libero, suscipit, quos. Quae praesentium tempore minima quod tempora odio',
            ),
            'item4' => array(// is odd
                'icon' => 'thumbs-o-up',
                'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
            ),
            'item5' => array(// is even
                'icon' => 'wrench',
                'content' => 'Debitis id eligendi assumenda, cumque optio veniam eos perferendis molestias explicabo odi',
            ),
        );

我想要做的是,当我循环遍历数组的元素以输出它们时,检测每个元素是奇数还是偶数,例如:

foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> (Item is odd or even) </p>'; // * Show wheather is odd or even here
}

5 个答案:

答案 0 :(得分:4)

只需声明一个计数器并进行迭代。

$counter = 1;
foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> ' . (($counter % 2)? 'odd': 'even') . ' </p>'; // * Show whether the position is odd or even here
    $counter++;
}

答案 1 :(得分:3)

$i = 1;
foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> ' . (($i % 2)? 'odd': 'even') . ' </p>'; // * Show wheather is odd or even here
    $i++;
}

答案 2 :(得分:1)

使用以下代码,您可以将$yourNumber替换为您要检查的变量。 if statement检查它是否为偶数,否则将在奇数时运行。

<?php
if ($yourNumber % 2 == 0) {
    echo "It is even.";
} else {
    echo "It is odd.";
}
?>

我们使用modulus检查它是否均匀。

答案 3 :(得分:1)

您可以使用计数器,模数运算符和数组将字符串映射到结果:

$map=['This item is: Even','Whilst this one is: Odd'];
$i=1;
foreach ($data as $key => $value): $i++;?>
    <h1> <?= $key;?> </h1>
    <p> <?= $value['icon'];?> </p>
    <p> <?= $value['content'];?> </p>
    <p> <?= $map[$i % 2];?> </p>
<?php endforeach;?>

答案 4 :(得分:0)

可以使用以下代码:

$i = 1;
 foreach ((array) $data as $key => $value) {
    if($i % 2 == 0) $item = 'even';
    else $item = 'odd';
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> (Item is '.$item.') </p>'; // * Show wheather is odd or even here
    ++$i;
}