PHP中从字符串中检查数组键是否存在

7

我有一个数组:

<?php
    $array = [
        'fruits' => [
            'apple' => 'value',
            'orange' => 'value'
        ],
        'vegetables' => [
            'onion' => 'value',
            'carrot' => 'value'
    ];

我也有一个字符串:

$string = 'fruits[orange]';

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

例如:

<?php
if(array_key_exists($string, $array)) 
{
    echo 'Orange exists';
}

3
使用类似于 $string 的字符串解析成数组看起来很奇怪。如果使用两个参数 $type$name,你的问题将更容易解决。 - Mcsky
如果字符串格式在您的控制范围内,则同意-考虑使用更容易解析的东西。 - iainn
$string的值是动态的还是静态的? - Adhan Timothy Younes
$str = explode(']', explode('[', $string)[1])[0]; array_walk_recursive($array, function($k, $v, $str){ if($v == $str){ echo " 找到了 $str"; } }, $str); - Christian Felix
5个回答

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.
}

1

如果反过来检查,会更容易。例如检查键是否在字符串中。由于键是唯一的,因此不可能有重复。

$array = [
  'fruits' => [
    'apple' => 'value',
    'orange' => 'value'
  ],
  'vegetables' => [
    'onion' => 'value',
    'carrot' => 'value'
  ]
];

$string = 'fruits[orange]';

$keys = array_keys($array['fruits']);

foreach($keys as $fruit) {
  if(false !== stripos($string, $fruit)) {
    return true;
  }
}

虽然这个解决方案不一定理想,但问题本身并不是很常见。

那么如果 OP 尝试查找 fruits[pineapple],但数组中只有键 apple,会发生什么情况呢?我认为你的解决方案需要进一步调整。(此外,如果数组可能具有大量键,则它的可扩展性相当差。) - Ilmari Karonen

1
你可以使用explode函数并检查数组的索引。
$array = array(
    'fruits' => [
        'apple' => 'value',
        'orange' => 'value'
    ],
    'vegetables' => [
        'onion' => 'value',
        'carrot' => 'value'
]);

$string = 'fruits[orange]';

$indexes = (preg_split( "/(\[|\])/", $string));
$first_index= $indexes[0];
$seconnd_index= $indexes[1];
if(isset($array[$first_index][$seconnd_index]))
{
    echo "exist";
}
else
{
    echo "not exist";
}

演示


1
你可以进行递归地步行:
$array = [
    'fruits' => [
       'apple' => 'value',
       'orange' => 'value'
    ],
   'vegetables' => [
       'onion' => 'value',
       'carrot' => 'value' 
    ]
];
$exists = false;
$search = "orange";
array_walk_recursive($array, function ($val, $key) use (&$exists,$search) {
     if ($search === $key) { $exists = true; }
});
echo ($exists?"Exists":"Doesn't exist");

打印:

存在

示例:http://sandbox.onlinephpfunctions.com/code/a3ffe7df25037476979f4b988c2f36f35742c217


1

与其他答案使用正则表达式或strpos不同,您也可以简单地在[上拆分$string,逐个解析键,直到只剩下一个键。然后将最后一个键与array_key_exists()结合使用来检查您的项。

这对于任何维度的工作都应该是有效的(例如fruit[apple][value][1])。

示例:

<?php

$arr = [
    'fruits' => [
        'orange' => 'value'
    ]
];

// Resolve keys by splitting on '[' and removing ']' from the results
$keys = 'fruits[orange]';
$keys = explode("[", $keys);
$keys = array_map(function($s) {
    return str_replace("]", "", $s);
}, $keys);

// Resolve item.
// Stop before the last key.
$item = $arr;
for($i = 0; $i < count($keys) - 1; $i++) {
    $item = $item[$keys[$i]];
}

// Check if the last remaining key exists.
if(array_key_exists($keys[count($keys)-1], $item)) {
    // do things
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接