如何检查数组键值是否包含元素

时间:2016-06-20 07:47:29

标签: php arrays array-key

我有一个像这样的数组

Array
(
    [0] => 
    [
        "18.06.2016",
        "18.06.2016",
        "18.06.2016",
        "Test Test",
        "Test Name",
        "Michael Dean",
        "London",
        "1",
        "980.00",
        "",
        "",
        "875.00",
        "875.00",
        "0",
        "64.81",
        "0",
        "810.19"
    ]
    [1] => 
    [
        "18.06.2016",
        "18.06.2016",
        "18.06.2016",
        "Tray 1",
        "Test Name",
        "Adam Richards",
        "London",
        "1",
        "980.00",
        "",
        "",
        "105.00",
        "105.00",
        "0",
        "7.78",
        "0",
        "97.22"
    ]...

我想在伦敦之后检查数组键值是否为1?

与第一个数组键一样,值类似于以下顺序:

...,“测试名称”,“迈克尔迪恩”,“伦敦”,“ 1 ”,...

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果订单总是一样,你可以循环。

foreach ($array as $key => $value) {
    if ($value[4] == 'London' && $value[5] == 1) {
        echo '$array['.$key.'] has London and 1 as key 4 and 5';
    }
}

虽然您尚未指定子阵列的键,但它们仍然具有默认键,您可以使用它们来获得所需的值。

修改

看一下你的数组,我发现按键顺序没有逻辑。除非您为town, id, date, name指定密钥,否则您将无法找到所需的值。

例如:

array(
    '0' => array(
        'name' => 'John Doe',
        'town' => 'London',
        'active' => 1,
    )

);

答案 1 :(得分:0)

使用常规foreach循环来检查London后面是否1值:

// $arr is your initial array
foreach ($arr as $k => $v) {
    if ($v[6] == 'London') {
        $hasValue = ($v[7] != 1)? "NOT" : "";
        echo "Item with key $k has 'London' which is $hasValue followed by 1". PHP_EOL;
    }
}

示例性输出:

Item with key 0 has 'London' which is  followed by 1
Item with key 1 has 'London' which is  followed by 1
...