download12749 2012-07-04 12:17
浏览 17
已采纳

将维度添加到1d数组

I've got an array called $bigArrayWithLinks that stores a string with a url in each element. Here's a sample from a 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)

What I want to do is iterate through the array, adding an integer of value '0' to each element so it becomes

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'

I tried:

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

I'm very new to php so I wasn't amazed that it didn't work. Could someone help me out please? Thanks in advance!

  • 写回答

3条回答 默认 最新

  • dongqiabei7682 2012-07-04 12:28
    关注

    You are confused about PHP arrays.

    An array is an index (or hash when using associative arrays) and it has 1(!) value. That value CAN be another array.

    You second example (what you wish) just shows:

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

    That doesn't make sense.

    I EXPECT what you are really looking for is some structure like this:

    $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)
    );
    

    That way you create an array of associative arrays. An associative array can use a descriptive key, like 'url' or 'score'. Now, if you want to add all scores:

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

    Or alternatively: create two seperate arrays: one with the URLs, the other with the scores. But you must make sure the indexes match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题