草庐IT

PHP递归函数错误?

coder 2024-04-12 原文

我创建了这个函数来在嵌套数组中搜索,但我一直为这个数组返回 null:

$arr3 = [
    'first' => 1,
    'second' => 2,
    'third' => [
        'fourth' => 4,
    ]
];

/**
 * returns the key for the first found value
 *
 * @param $needle
 * @param array $haystack
 * @return false|int|string
 */
function array_search_value($needle, array $haystack) {

    $result = null;
    $found = array_search($needle, $haystack);

    if ( $found !== false ) {
        // end the recursion
        $result = $found;

    } else {
        foreach ($haystack as $key => $item) {
            if (is_array($item)) {
                array_search_value($needle, $item);
            } else {
                continue;
            }
        }
    }

    return $result;
}

var_dump(array_search_value(4, $arr3));

我不知道我做错了什么? var_dump() 结果应该是 string "fourth"

最佳答案

如果您在递归过程中找到了您正在寻找的东西,您实际上并没有将它存储在任何地方。这是我推荐的方法:

$arr3 = [
    'first' => 1,
    'second' => 2,
    'third' => [
        'fourth' => 4,
    ]
];

/**
 * returns the key for the first found value
 *
 * @param $needle
 * @param array $haystack
 * @return null|array
 */
function array_search_value($needle, array $haystack) {

    $result = null;
    $found = array_search($needle, $haystack);

    if ( $found !== false ) {
        // end the recursion
        $result = [ $found ]; //Array will make sense in a bit

    } else {
        foreach ($haystack as $key => $item) {
            if (is_array($item)) {
                $found = array_search_value($needle, $item);
                if ($found !== null) {
                   return array_merge([$key],$found);
                }
            } else {
                continue;
            }
        }
    }

    return $result;
}

var_dump(array_search_value(4, $arr3));

返回数组的原因是为了防止子数组与主数组具有相同的键,这样您就可以通过递归访问返回的每个数组条目的数组索引来始终如一地检索正确的键。

查看代码:http://sandbox.onlinephpfunctions.com/code/085c949f660504010ed7ebb7a846e31b3a766d61

下面是一个例子,说明为什么需要返回一个数组:

如果考虑数组:

$arr3 = [
    'a' => 1,
    'b' => 2,
    'c' => [
        'a' => 4,
    ],
    "d"=>[
        "a" => [
            "a" => 19    
        ]
    ]
];

如果您要查找 4 而不是返回数组,您将返回 a 但这也将是不明确的,因为 a 在根数组中包含 1

http://sandbox.onlinephpfunctions.com/code/43c2f2dfa197400df1e5748e12f12e5346abed3e

如果有多个路径,您可以修改上面的内容以获取通向给定结果的所有路径。

function array_search_value_all($needle, array $haystack) {

    $result = [];
    $found = array_search($needle, $haystack);

    if ( $found !== false ) {
        // end the recursion
        $result[] = [ $found ]; //Array will make sense in a bit

    } else {
        foreach ($haystack as $key => $item) {
            if (is_array($item)) {
                $found = array_search_value($needle, $item);
                if ($found !== []) {
                   $result[] = array_merge([$key],$found);
                }
            } else {
                continue;
            }
        }
    }

    return $result;
}

array_search_value_all 将返回指向该值的所有路径的数组。

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

关于PHP递归函数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54588814/

有关PHP递归函数错误?的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐