duanbi8089 2016-03-27 00:01 采纳率: 100%
浏览 208

在多维数组中查找值

I have to find value in a multidimensional array, size of array is not defined. Let suppose user enters 1601 , result will be 011. and if 1605 , the result will be 015 according to array

   array (size=6)
      0 => 
        array (size=2)
          0 => string 'Zipcode' (length=7)
          1 => string 'Territory Code' (length=14)
      1 => 
        array (size=2)
          0 => string '1601' (length=4)
          1 => string '011' (length=3)
      2 => 
        array (size=2)
          0 => string '1602' (length=4)
          1 => string '012' (length=3)
      3 => 
        array (size=2)
          0 => string '1603' (length=4)
          1 => string '013' (length=3)
      4 => 
        array (size=2)
          0 => string '1604' (length=4)
          1 => string '014' (length=3)
      5 => 
        array (size=2)
          0 => string '1605' (length=4)
          1 => string '015' (length=3)
  • 写回答

1条回答 默认 最新

  • dshu1235 2016-03-27 00:08
    关注

    If Zipcode is unique then you can do:

    echo array_column($array, 1, 0)[1601];
    

    Or if Territory Code is unique:

    echo array_search(1601, array_column($array, 0, 1), true);
    

    array_column() extracts a column from the multi-dimensional array to create a one dimensional array.

    array array_column ( array $input , mixed $column_key [, mixed $index_key = null ] )

    The second parameter $column_key defining which column you want to get from the multidimensional array as values into the one dimensional array. And the third parameter $index_key defining which column you want to use as keys for the one dimensional array which you get back. If $index_key is not defined, the array will be numerical enumerated.

    First code example

    So the first example extracts an array such as:

    array(1601 => '011', 1602 => '012')
    

    Using the value 1601 as the key you get the desired output 011.

    Second code example

    The second example uses an array such as:

    array('011' => 1601, '012' => 1602)
    

    And searches for 1601 with array_search() to get the key 011, which is the desired output.

    See these two examples for what the second and third parameters do:

    print_r(array_column($array, 1, 0));
    print_r(array_column($array, 0, 1));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探