将维度添加到 1D 数组


add dimension to 1d array

>我有一个名为$bigArrayWithLinks的数组,它存储了一个字符串,每个元素中都有一个url。下面是一个var_dump示例:

array
  0 => string 'http://en.wikipedia.org/wiki/England' (length=36)
  1 => string 'http://www.bbc.co.uk/news/england/' (length=34)
  2 => string 'http://www.thefa.com/' (length=21)
  3 => string 'http://www.thefa.com/England/' (length=29)

我想做的是遍历数组,为每个元素添加一个值为"0"的整数,使其变为

array
  0 => string 'http://en.wikipedia.org/wiki/England' => int '0'
  1 => string 'http://www.bbc.co.uk/news/england/'  => int '0'
  2 => string 'http://www.thefa.com/'  => int '0'
  3 => string 'http://www.thefa.com/England/'  => int '0'

我试过了:

for($x=0; $x<sizeof($arr); $x++)
{
    $score = $arr[$x]['score'];
    $score = '0';
}

我对 php 很陌生,所以我对它不起作用并不感到惊讶。有人可以帮我吗?提前感谢!

你对PHP数组感到困惑。

数组

是一个索引(或使用关联数组时为哈希),它的值为 1(!)。该值可以是另一个数组。

您的第二个示例(您希望的)仅显示:

0 => string 'http://en.wikipedia.org/wiki/England' => int '0'

这说不通。

我希望您真正要寻找的是这样的结构:

$mySiteScore = array(
 array('url'=>'http://en.wikipedia.org/wiki/England', 'score' =>0),
 array('url'=>'http://www.bbc.co.uk/news/england/', 'score' =>0),
 array('url'=>'http://www.thefa.com/', 'score' =>0)
);

这样,您就可以创建关联数组的数组。关联数组可以使用描述性键,例如"url"或"score"。现在,如果要添加所有分数:

$totalScore = 0;
foreach ($mySiteScore as $oneSiteScore){
  $totalScore = $totalScore  + $oneSiteScore['score'];
}

或者:创建两个单独的数组:一个包含 URL,另一个包含分数。但必须确保索引匹配。

foreach($bigArrayWithLinks as $key => $url) {
  $bigArrayWithLinks[$key] = array('url' => $url, 'x' => 0);
}

只需制作另一个零的 1D 数组,索引将是相同的。

在几乎所有编程语言中,如果不重新分配和复制到新容器,"新维度"是不可能的。