cakephp hash返回键,如果子值与某些内容相匹配



我从来没有真正使用过cakephp hash公用事业类,很抱歉,如果这是一个简单的问题。我正在网上阅读该文档,我不确定是否可以做我想做的。

如果子值匹配某些东西,是否有一种方法可以使用哈希返回路径的值之一。例如,如果我有一个数组

$test_array = [123 => ['name' => 'foo'], 234 => ['name' => 'bar']];

我想根据我测试的"名称"的值返回123或234,我可以使用下面的代码以获取键吗?

$return_value = Hash::extract($test_array, '{n}.[text=/foo/]');

我自己找到了答案,它不像我想要的那样灵活,但它适用于我的特定情况。

//initial array
$test_array = [123 => ['name' => 'foo'], 234 => ['name' => 'bar']];
//convert to collection
$test_collection = collection($test_array);
//filter collection to get only what we want
$collection_filtered = $test_collection->match(['name' => 'bar']);
//convert collection back to array [234 => ['name' => 'bar']]
$collection_to_array = $collection_filtered->toArray();
//use php functions array_keys() and reset() to get the appropriate value
$key = reset(array_keys($collection_to_array));
echo $key; //$key = 234
//can also be written in one line like so
$key = reset(array_keys(collection($test_array)->match(['name' => 'bar'])->toArray()));

最新更新