【问题标题】:How can i get the parent key and value if i already have children value of an array?如果我已经有一个数组的子值,如何获取父键和值?
【发布时间】:2020-06-07 19:00:47
【问题描述】:

我无法弄清楚如何借助多维数组的子键值来获取父键和值。

我有一个格式如下的数组:

[91] => Array
    (
        [description] => Charged
        [boundingPoly] => Array
            (
                [vertices] => Array
                    (
                        [0] => Array
                            (
                                [x] => 244
                                [y] => 438
                            )

                        [1] => Array
                            (
                                [x] => 287
                                [y] => 438
                            )

                        [2] => Array
                            (
                                [x] => 287
                                [y] => 452
                            )

                        [3] => Array
                            (
                                [x] => 244
                                [y] => 452
                            )

                    )

            )

    )

我正在获取并存储键 ['x'] 的值:

foreach($array as $box){
     if($box['description']=="Charged"){
            $lbl_row_arr[] = $box['boundingPoly']['vertices'][0]['x'];
     }
}

所以现在我在这个例子中的“x”值是“244”。我的问题是,如果我有 'x' 的值,我如何获得 'description' 键的值?

【问题讨论】:

    标签: php arrays arraylist multidimensional-array array-key


    【解决方案1】:

    您可以使用in_array 和array_column 来搜索每个框的x 值,如果找到x 值,则返回该框的description:

    $x = 244;
    foreach ($array as $box) {
        if (in_array($x, array_column($box['boundingPoly']['vertices'], 'x'))) {
            $descr = $box['description'];
            break;
        }
    }
    if (isset($descr)) {
        echo "found $descr with x = $x\n";
    }
    

    输出(用于您的示例条目):

    found Charged with x = 244
    

    Demo on 3v4l.org

    【讨论】:

      【解决方案2】:

      将description值与x值同时放入:

      foreach($array as $box){
           if($box['description']=="Charged"){
                  $tmp = [
                      'value_x' => $box['boundingPoly']['vertices'][0]['x'],
                      'descr'   => $box['description'], 
                  ];
                  $lbl_row_arr[] = $tmp;
           }
      }
      
      $x = 244;
      echo $lbl_row_arr[array_search($x,array_column($lbl_row_arr,'value_x'))]['descr'];
      

      【讨论】:

        猜你喜欢
        • 2020-12-10
        • 1970-01-01
        • 2015-05-18
        • 2020-11-30
        • 2016-06-25
        • 2016-07-05
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        相关资源
        最近更新 更多