简体   繁体   English

array_key_exists无法正常工作

[英]array_key_exists not working as expected

Problem 问题

I'm having trouble using the PHP function array_key_exists . 我在使用PHP函数array_key_exists遇到麻烦。 Even though my array has the key, the function always returns false. 即使我的数组具有键,该函数也始终返回false。 I wonder if there is a issue regards using a dynamically growing array. 我想知道使用动态增长的数组是否存在问题。 I'm new to PHP, sorry if the question is annoying trivial. 我是PHP的新手,很抱歉,如果这个问题很烦人。

Expected behavior 预期行为

I need the array_key_exists function returning true if the array has the key. 如果数组具有键,我需要array_key_exists函数返回true。

What I tried to solve 我试图解决的问题

I tried to use isset(CounterArray[$key]) instead but I got no success. 我尝试使用isset(CounterArray[$key])代替,但没有成功。

I've already read the PHP docs, for the specific function and I've also checked similar questions on stack-overflow but none of them were suitable for my case. 我已经阅读了有关特定功能的PHP文档,并且还检查了关于堆栈溢出的类似问题,但是没有一个适合我的情况。 I'm shamefully expending a huge time with this. 我为此花了大量时间可耻。

code

$values=[
        "a"=>100,
        "a"=>100,
        "a"=>100,
        "b"=>200,   
    ];


    $counterArray = array();

    foreach ($values as $key => $price) {

        if(!array_key_exists( $key , $counterArray))){
            $counterArray[$key]=$price;

        }else{

            $counterArray[$key] += $price;

        }
    }

Your $values array contains duplicates of the same key 'a' , which will be ignored. 您的$values数组包含相同键'a'重复项,它将被忽略。 Thus, $counter_array will end up containing an exact copy of $values . 因此, $counter_array最终将包含$values的精确副本。

It sounds like $values should be an array of arrays, eg: 听起来$values应该是一个数组数组,例如:

$values = [
    ["a"=>100],
    ["a"=>100],
    ["a"=>100],
    ["b"=>200],
];

Of course, your loop will have to change accordingly: 当然,您的循环将必须进行相应的更改:

foreach ($values as $a) {
    list( $key, $price ) = $a;
    // ...

It's because your actual array is internally like array(2) { ["a"]=> int(100) ["b"]=> int(200) You will get above output when you do var_dump($values); 这是因为您的实际数组在内部就像array(2){[“” a“] => int(100)[” b“] => int(200)当执行var_dump($ values)时,您将得到上面的输出; In your code 在你的代码中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM