1

我正在尝试构建一个 az, 0-9 的数组,每个数组都有一个相同数组的子集。

IE:

array(
   "a"=>array("a","b","c"..."0","1","2")
   "b"=>array("a","b","c"..."0","1","2")
   "c"=>array("a","b","c"..."0","1","2")
   "d"=>array("a","b","c"..."0","1","2")
   "0"=>array("a","b","c"..."0","1","2")
   "1"=>array("a","b","c"..."0","1","2")
   "2"=>array("a","b","c"..."0","1","2")
   "3"=>array("a","b","c"..."0","1","2")
)

我在哪里尝试这个

$finalArr = array();
$letterArr = range('a', 'z');
$numericArr = range(0,9);
$startArr = array_merge($letterArr, $numericArr);

foreach($startArr as $key => $val)
{
    $finalArr[$val] = $startArr;
    foreach($finalArr[$val] as $key2 => $val2)
    {
        $finalArr[$val][$val2] = $startArr;
    }


}

但它只适用于第一遍......之后它开始变得一团糟。有任何想法吗?

4

3 回答 3

2

您在循环遍历数组时正在修改数组;这不是一个好的做法,在这种情况下甚至没有必要。

也就是说,您可以array_fill_keys()像这样使用:

$arr = str_split('abcdefghijklmnopqrstuvwxyz0123456789');
$final = array_fill_keys($arr, $arr);
于 2013-09-09T06:40:36.637 回答
0

这是因为您在内循环下使用了相同的数组名称

foreach($finalArr[$val] as $key2 => $val2)
    {
        $finalArr[$val][$val2] = $startArr;
    }

声明一个新数组 $finalArr2 = array() 并将代码更改为

foreach($finalArr[$val] as $key2 => $val2)
    {
        $finalArr2[$val][$val2] = $startArr;
    }

它现在应该可以工作了。

于 2013-09-09T06:35:54.697 回答
0

要使用现有逻辑,您需要unset($finalArr[$val][$key2]);清除临时存储的数组。

$finalArr = array();
$letterArr = range('a', 'z');
$numericArr = range(0,9);
$startArr = array_merge($letterArr, $numericArr);

foreach($startArr as $key => $val)
{
    $finalArr[$val] = $startArr;
    foreach($finalArr[$val] as $key2 => $val2)
    {
        unset($finalArr[$val][$key2]);
        $finalArr[$val][$val2] = $startArr;
    }    
}

如果你想要一些更清晰的逻辑,这更有意义。

foreach($startArr as $val)
{
    foreach($startArr as $val2)
    {                                 
        $finalArr[$val][$val2] = $startArr;
    }
}
于 2013-09-09T06:41:03.590 回答