dtcn30461 2016-10-17 10:29
浏览 30
已采纳

查找单个数组中每个数组的函数

hey guys please help me out with this. am trying to write a function that finds every array within and array then modify all arrays found.

I have achieved the first goal, the second not quite.

here is the function so far.

  $count = 0;
  function findObj($arr) {
    global $count;

    foreach($arr as $key => $value) {
      if(gettype($arr[$key]) == 'array') {
        // append the string "here" to the array found
        $arr[$key][] = 'here';
        $count++;
        // call same function within function with the argument of array found
        findObj($arr[$key]);
      }
    }

    $rtnArr = [$count, $arr];
    return $rtnArr;
  }

  var_dump(findArr($arr));
  // this returns

  array (size=5)
  0 => int 1
  1 => int 44
  2 => int 43
  3 => 
    array (size=2)
      0 => string 'hello' (length=5)
      1 => string 'here' (length=4)
  4 => 
    array (size=4)
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => 
        array (size=2)
          0 => string 'three' (length=5)
          1 => string 'four' (length=4)
      3 => string 'here' (length=4)

only the arrays in the first level where modified. please help my brain is about to explode().

  • 写回答

1条回答 默认 最新

  • dsxcv5652 2016-10-17 14:28
    关注
    <?php
    $input =
    [
        [
            'foo',
            [
                'bar',
                'baz',
                [
                    'bat',
                    'man'
                ]
             ]
        ]
    ];
    
    function add_extra_element_recursive(array &$array)
    {
        foreach($array as $key => &$value) {
            if(is_array($value)) {
                add_extra_element_recursive($value);
            }
        }
        $array[] = 'extra';
    }
    
    var_export($input);
    echo "
    ";
    add_extra_element_recursive($input);
    var_export($input);
    

    Output:

    array (
      0 => 
      array (
        0 => 'foo',
        1 => 
        array (
          0 => 'bar',
          1 => 'baz',
          2 => 
          array (
            0 => 'bat',
            1 => 'man',
          ),
        ),
      ),
    )
    array (
      0 => 
      array (
        0 => 'foo',
        1 => 
        array (
          0 => 'bar',
          1 => 'baz',
          2 => 
          array (
            0 => 'bat',
            1 => 'man',
            2 => 'extra',
          ),
          3 => 'extra',
        ),
        2 => 'extra',
      ),
      1 => 'extra',
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?