【问题标题】:how to fill empty multidimensional array in php?如何在php中填充空的多维数组?
【发布时间】:2014-04-17 15:09:40
【问题描述】:

我想使用函数array_push 来填充一个空数组,但是我得到一个错误,参数 1 应该是数组但给出了 null,这是我的代码:

public $docs = array("ant ant bee", "dog bee dog hog dog ant dog", "cat gnu eel fox");

public function terms(){

    $temp = array();
    $terms = array(array());
    $docs = $this->docs;

    for($i = 0; $i < sizeof($docs); $i++){

        $temp[$i] = preg_split('/ /', $docs[$i], null, PREG_SPLIT_NO_EMPTY);
    }           

    for($i = 0; $i < sizeof($temp); $i++){

        for($j = 0; $j < sizeof($temp[$i]); $j++){

            for($k = 0; $k < sizeof($temp[$i]); $k++){

                if($temp[$i][$j] != $terms[$i][$k])

                    array_push($terms[$i], $temp[$i][$k]);
            }
        }
    }

    return $terms;
}
}

【问题讨论】:

  • 你想要什么结果?这看起来过于复杂。
  • 您希望每个新元素(以空格分隔)都位于新级别的数组中吗?你想要多少级?不能真正得到你想做什么xd
  • 错误很明显,只要按照你的代码,你会看到$terms[1]没有设置。
  • @aleation in $temp 我想在拆分后存储文档字符串,然后在$terms 我想从每个子数组存储唯一的字符串,所以每个重复的字符串都应该存储一次对于每个子数组
  • @user3194430 你应该添加你想要的结果数组的样子。

标签: php arrays multidimensional-array push


【解决方案1】:

根据您对预期结果的评论,应该这样做或非常接近:

foreach($this->docs as $value) {
    $terms[] = array_unique(array_filter(explode(' ', $value)));
}    
return $terms;

【讨论】:

  • 它非常简单有效
【解决方案2】:

我不确定你对所有这些循环做了什么,但你当前的问题很容易通过改变来解决:

array_push($terms[$i], $temp[$i][$k]);

到:

$terms[$i][] = $temp[$i][$k];

这与array_push() 的作用相同,不同之处在于如果$terms[$i] 尚不存在,则会自动创建它。

【讨论】:

    【解决方案3】:

    可以如下实现

    function terms(){   
        $docs = array("ant ant bee", "dog bee dog hog dog ant dog", "cat gnu eel fox");
        $temp = array();
        $terms = array();
    
        for($i = 0; $i < sizeof($docs); $i++){
            $temp[$i] = preg_split('/ /', $docs[$i], null, PREG_SPLIT_NO_EMPTY);
        } 
        foreach ($temp as $key => $value) {
            $temp[$key] = array_unique($value); 
        } 
        return $temp; 
    }
    

    【讨论】:

      【解决方案4】:

      不确定声明 $terms = array(array()); 是否符合您的要求....

      方案一:先初始化$terms

      $terms = array();
      
      for($i = 0; $i < sizeof($docs); $i++){
          $terms[$i] = array();
      }
      

      或者更好:插入

      $terms[$i] = array();
      

      进入您现有的循环:您初始化$temp 的循环,或第二个for($i...) 循环,就在for($j ...) 之前

      解决方案 2:在使用 array_push 之前测试 terms[$i]

      for ($i ...) {
          for ($j ...) {
              for ($k ...) {
                  if (!is_array($terms[$i])) $terms[$i] = array();
                  // your stuff here
              }
          }
      }
      

      但我更喜欢第一种解决方案...

      【讨论】:

        猜你喜欢
        • 2017-01-25
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 2018-01-27
        • 1970-01-01
        • 2022-01-19
        • 2015-09-28
        相关资源
        最近更新 更多