【问题标题】:Cakephp Hash return key if sub value matches something如果子值匹配某些东西,Cakephp 哈希返回键
【发布时间】:2018-04-11 07:34:05
【问题描述】:

我从未真正使用过 Cakephp Hash 实用程序类,如果这是一个简单的问题,我很抱歉。我正在在线阅读文档,我不确定我是否可以做我想做的事情。

如果子值匹配某些东西,有没有办法使用哈希返回路径中的一个值。例如,如果我有一个数组

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

我想根据我测试的“名称”的值返回 123 或 234,我可以使用类似于下面的代码来获取密钥吗?

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

【问题讨论】:

  • 哈希已被弃用。你用的是什么版本的 cakephp?
  • @arilia 哈希已弃用?从何时起?在当前的 3.5 书中没有提到这一点:book.cakephp.org/3.0/en/core-libraries/hash.html
  • 你是对的,对不起。我认为 Collections 已弃用 Hash,但我发现两者仍然存在

标签: cakephp hash


【解决方案1】:

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

//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()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 2015-04-25
    • 2022-01-17
    • 1970-01-01
    • 2017-04-18
    • 2014-04-07
    • 2010-10-28
    • 2015-09-17
    相关资源
    最近更新 更多