【问题标题】:PHP computed associative array keys?PHP计算关联数组键?
【发布时间】:2021-03-23 19:35:17
【问题描述】:

我想创建一个带有计算键的关联数组,例如:

    if ($arr[$mid]["something"] == $x) {
        $foundPlaces = Array(
            `$computedKey` => $arr[$mid]["some_other"];
        )
        print_r($foundPlaces);
        return $foundPlaces; 
    }

我使用 binSearch 根据某个键搜索数组 Values,如果该键存在,我想创建一个关联数组,其中键作为计算值(而不是字符串)并为其分配相应的找到值用它键并返回数组...

上面的语法不起作用,我知道它在带有括号和[key]左右的Javascript中是可能的,但不知道它在php中是如何工作的?

【问题讨论】:

  • 您的问题到底是什么?变量可以用作数组键。
  • 好的,我简单地使用了 'sometring' => 键和 'otherstring' => 值并返回了数组...我认为像 Javascript 中的对象上的计算字段之类的东西是可能的..

标签: php key associative-array computed-properties


【解决方案1】:

你很亲密,我想它会帮助你:

    if ($arr[$mid]["something"] == $x) {
        // $computedKey = "result_of_computing"; // can be like this
        // $computedKey = 18; // or like this
        $foundPlaces = [
            $computedKey => $arr[$mid]["some_other"];
        ]
        print_r($foundPlaces);
        return $foundPlaces; 
    }

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2013-10-10
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多