如何获取特定的数组元素值

时间:2016-03-11 18:22:03

标签: php arrays for-loop

这是我的样本数组:

$my_array = Array
(
    [0] => 
    [1] => Seasons:
    [2] => Winter
    [3] => Spring
    [4] => Summer
    [5] => Fall
    [6] => 
    [7] => Color List:
    [8] => Blue
    [9] => Green
    [10] => Yellow
    [11] => Cyan
    [12] => Red 
    [13] => 
    [14] => Showing the Following Fruits:
    [15] => Kiwi
    [16] => Apple
    [17] => Banana
    [18] => Mango
    [19] => Watermelon
    [20] => Orange
)

我想要的输出是这样的:

示例输出:

如果它看到单词“Fruits”,它将只打印数组元素编号14到20

Showing the Following Fruits:
Kiwi
Apple
Banana
Mango
Watermelon
Orange

如果它看到单词“Color”,它将打印出阵列元素编号7到20,这是数组的末尾

Color List:
Blue
Green
Yellow
Cyan
Red 

Showing the Following Fruits:
Kiwi
Apple
Banana
Mango
Watermelon
Orange

获得此输出的最佳方法是什么?

但是我不知道如何获取索引的值。在我的第一个例子中,元素编号为14

在研究时我发现有些人使用array_search来获取数组元素的值。

$searchval = array_search("Showing the Following Fruits:",array_values($retval));

但是,上面的代码要求您输入数组的完整值[14]。

无论如何我可以输入“水果”而不是“显示以下水果”值吗?

请参阅下面的代码:

for ($i = $searchval; $i <= count($my_array); $i++)
{
    echo "<pre>".$my_array[$i]."</pre>";
}

2 个答案:

答案 0 :(得分:1)

执行while循环检查关键字,然后读取所有字符串,直到达到下一个空值。

答案 1 :(得分:0)

只需使用多维数组并使用foreach循环遍历它。例如以下内容:

select * from event_schedule as t1 
JOIN ( 
    SELECT DISTINCT(event_id) as e 
    from event_schedule 
    GROUP BY event_id 
    order by MAX(end < unix_timestamp(now())) asc, 
             MIN(start >= unix_timestamp(now())) asc, 
             MAX(start) desc 
             limit 0, 20 
    ) 
    as t2 on (t1.event_id = t2.e)

将返回:

<?php
$array = array("Seasons" => array(1 => "Winter", 2 => "Spring", 3 => "Summer", 4 => "Fall"));

echo "Seasons:\n";
foreach ($array["Seasons"] as $season) {
    echo $season . "\n";
}
?>

编辑:

或者,如果您想要维护当前的数组格式,则可以使用foreach循环并在返回元素之前检查数组中键的值。例如:

Seasons:
Winter
Spring
Summer
Fall

将返回此:

<?php
$my_array = Array
(
    1 => "Seasons:",
    2 => "Winter",
    3 => "Spring",
    4 => "Summer",
    5 => "Fall",
    6 => " ",
    7 => "Color List:",
    8 => "Blue",
    9 => "Green",
    10 => "Yellow",
    11 => "Cyan",
    12 => "Red",
    13 => " ",
    14 => "Showing the Following Fruits:",
    15 => "Kiwi",
    16 => "Apple",
    17 => "Banana",
    18 => "Mango",
    19 => "Watermelon",
    20 => "Orange"
);

foreach ($my_array as $key => $value) {
    if ($key >= 7 && $key <= 12) {
        echo $value . "\n";
    }
}
?>