PHP数组键存在于string中

CDR*_*CDR 8 php arrays string

我有一个数组:

<?php
    $array = [
        'fruits' => [
            'apple' => 'value',
            'orange' => 'value'
        ],
        'vegetables' => [
            'onion' => 'value',
            'carrot' => 'value'
    ];
Run Code Online (Sandbox Code Playgroud)

我也有一个字符串:

$string = 'fruits[orange]';
Run Code Online (Sandbox Code Playgroud)

有没有办法检查字符串中指定的 - 数组键 - 是否存在于数组中?

例如:

<?php
if(array_key_exists($string, $array)) 
{
    echo 'Orange exists';
}
Run Code Online (Sandbox Code Playgroud)

Sah*_*ati 4

试试这个。这里我们使用的是foreachisset函数。

注意:此解决方案也适用于更深层次,例如: fruits[orange][x][y]

在这里尝试这个代码片段

<?php

ini_set('display_errors', 1);
$array = [
    'fruits' => [
        'apple' => 'value',
        'orange' => 'value'
    ],
    'vegetables' => [
        'onion' => 'value',
        'carrot' => 'value'
    ]
];
$string = 'fruits[orange]';
$keys=preg_split("/\[|\]/", $string, -1, PREG_SPLIT_NO_EMPTY);
echo nestedIsset($array,$keys);
function nestedIsset($array,$keys)
{
    foreach($keys as $key)
    {
        if(array_key_exists($key,$array))://checking for a key
            $array=$array[$key];
        else:
            return false;//returning false if any of the key is not set
        endif;
    }
    return true;//returning true as all are set.
}
Run Code Online (Sandbox Code Playgroud)