gpt4 book ai didi

php - 查找具有特定键名前缀的数组元素

转载 作者:搜寻专家 更新时间:2023-10-31 21:07:11 24 4
gpt4 key购买 nike

我有一个包含很多元素的关联数组,我想获得一个包含具有特定前缀的键名的所有元素的列表。

例子:

$arr = array(
'store:key' => 1,
'user' => 'demo',
'store:foo' => 'bar',
'login' => true,
);

// this is where I need help with:
// the function should return only elements with a key that starts with "store:"
$res = list_values_by_key( $arr, 'store:' );

// Desired output:
$res = array(
'store:key' => 1,
'store:foo' => 'bar',
);

最佳答案

你可以简单地做:

$arr = array(
'store:key' => 1,
'user' => 'demo',
'store:foo' => 'bar',
'login' => true,
);

$arr2 = array();
foreach ($arr as $array => $value) {
if (strpos($array, 'store:') === 0) {
$arr2[$array] = $value;
}
}
var_dump($arr2);

返回:

array (size=2)
'store:key' => int 1
'store:foo' => string 'bar' (length=3)

关于php - 查找具有特定键名前缀的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com