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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面