douyuan9512 2012-08-19 13:45
浏览 36

如何更深入的多维数组索引? [关闭]

Code:

$a = array();
$a[] = 'a';
$a[] = 'b';
$a[] = 'c';
$a[] = array('e', 'f', array('g', '3'), 'c');
$a[] = 'd';

this works fine:

return $a[3][2][1];

it gives "3". But what if I need to do it with programmatically? A searching or something?

  • 写回答

3条回答 默认 最新

  • dsa4d4789789 2012-08-19 13:49
    关注

    You could use array_walk_recursive to go through each element of the array including array elements, but you might be better off using an OOP approach and making objects of the items (and possibly hilding an array inside them) which would make it much more intuitive.

    Example of array_walk_recursive:

    <?php
    $sweet = array('a' => 'apple', 'b' => 'banana');
    $fruits = array('sweet' => $sweet, 'sour' => 'lemon');
    
    function test_print($item, $key)
    {
        echo "$key holds $item
    ";
    }
    
    array_walk_recursive($fruits, 'test_print');
    ?>
    

    output:

    a holds apple
    b holds banana
    sour holds lemon
    

    An example of a class would be as follows:

    class mySubArray
    {
        public $element1='e';
        public $element2='f';
        public $element3=array();
        public $element4='c';
    }
    
    class mySomething
    {
        public $var1='a';
        public $var2='b';
        public $var3='c';
        public $var4=array();
        public $var5='d';
    
        public function __construct()
        {
            $this->var4= new mySubArray();
            $this->var4->element3[0]='g';
            $this->var4->element3[0]='3';
        }
    }
    
    $myObject = new mySomething();
    

    Then you can access the properties as follows:

    echo $myObject->var3; // Output: c
    echo $myObject->var4->element2; // output: f
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)