簡體   English   中英

PHP通過關聯數組循環

[英]PHP Loop through an associative array

根據評論進行編輯以提供澄清。

我有一個動態的關聯數組,其鍵和值如下所示:

array: ["apples" => 4   "bananas" => 4   "cherries" => 4   "dates" => 3]

我想創建另一個n大小的數組(帶有動態n),該數組將循環遍歷該數組。

例:

(if n = 6):

apples, cherries, apples
bananas, dates, bananas
cherries, apples, cherries
dates, bananas
apples, cherries
bananas, dates

n范圍介於1和所有值的總和之間

我到目前為止的代碼是這樣的:

function makeArray($commonWords){
  $n = 6;
  $result = array_fill(0,$n, '');
  $i = 0;

  while (list($key, $value) = each($commonWords)) {
    $result[$i] = $result[$i] . $key;
    $i++;
  }

  return $result;
}

提供以下輸出:

array:6 [▼
  0 => "apples"
  1 => "bananas"
  2 => "cherries"
  3 => "dates"
  4 => ""
  5 => ""
]

但是第五行必須是“ apples”,第六行需要是“ bananas”。 然后,在第一行中,“蘋果”之后需要有“櫻桃”,依此類推,如上例所示。

希望這可以澄清。

如果我正確理解了您的問題,我認為我有解決方案。

我將$n添加到參數列表,而不是在函數內部定義它。

function makeArray($commonWords,$n=6){
    $result = array_fill(0,$n,'');
    $c = 0;
    // while we still have words to print out
    while(array_sum($commonWords)){
        foreach($commonWords as $word=>$number){
            // if this word is still available
            if($number > 0){
                // put the separator if we have looped through at least once
                if($c >= $n){
                    $result[($c % $n)] .= ", ";
                }
                $result[($c % $n)] .= $word;
                // reduce the number of this word available
                $commonWords[$word]--;
                $c++;
            }
        }
    }
    return $result;
}

目前尚不清楚您要完成什么,但是您可以執行以下操作。

您在這里描述的是

但是第五行必須是“ apples”,第六行需要是“ bananas”。

循環鏈表 但是由於迭代次數不能超過給定數組的總和,因此這是一個循環的帶有限制的鏈表。 您可以在Wiki中閱讀有關鏈接列表的信息。

幸運的是,PHP在標准PHP庫中具有SplDoublyLinkedList類。 但是我們必須對其進行一些調整以滿足我們的需求:

class CircularLinkedListWithLimit extends SplDoublyLinkedList
{
    protected $limit;

    public function __construct($limit)
    {
        $this->limit = $limit;
    }

    public function next()
    {
        $this->limit -= 1;
        parent::next();
    }

    public function valid()
    {
        return $this->limit > 0 
            ? parent::valid() || $this->rewind() || true
            : false;
    }
}

有了此類,我們可以創建列表:

$array = ["apples" => 4, "bananas" => 4, "cherries" => 4, "dates" => 3];

$limit = array_sum($array);
$list = new CircularLinkedListWithLimit($limit);

foreach ($array as $key => $_) {
    $list->push($key);
}

有了這個循環列表,我們就可以填充我們的表(為簡單起見,我在這里硬編碼$n ,但是您可以將其包裝在函數中):

$n = 6;

$i = 0;
$j = 0;
$table = array_fill($i, $n, []);

foreach ($list as $item) {
    $table[$i][$j] = $item;

    $i += 1;

    if ($i >= $n) {
        $i = 0;
        $j += 1;
    }
}

有了這張桌子,您可以做自己喜歡的事情。 當您提供了一些預期的輸出時,下面是將其打印出來的代碼:

echo implode(PHP_EOL, array_map(function ($row) {
    return implode(', ', $row); 
}, $table));

這將導致

apples, cherries, apples
bananas, dates, bananas
cherries, apples, cherries
dates, bananas
apples, cherries
bananas, dates

這是工作演示

如您所見,幾乎我們所有的工作都是使用內置功能,並通過簡單的非嵌套循環將其引導以適應我們的需求。 這實際上是使用高級編程語言進行編程的目標。 因為您編寫的代碼較少,所以引入系統的錯誤也較少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM