dongqu7778 2013-12-07 23:25
浏览 23
已采纳

了解foreach循环中的变量赋值[关闭]

I have a pretty basic question:

What is this statement actually doing (specifically the =>$p)?

foreach ($email->parts as $partno=>$p) {

I understand the the basics but the =>$p is not clear

  • 写回答

3条回答 默认 最新

  • duanniesui6391 2013-12-07 23:27
    关注

    In a foreach loop you can ask for both the key and value to be returned

    $array = array('cat' => 'Tom', 'mouse' => 'Jerry');
    foreach($array as $animal => $name) {
        echo $name . ' is a ' . $animal . '<br>';
    }
    

    So the loop will output

    Tom is a cat
    Jerry is a mouse

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douduan5086 2013-12-07 23:27
    关注

    This synthax is to assign the array key name or object property name to the variable $partno and it's value to $p.

    This way you can do for instance $email->parts[$partno] = $p;.

    It can be particularly useful if you have parallel arrays with different information bound by the key, so you need this information to obtain related data from the other array when iterating one of them.

    For instance:

    $person = array(
        1 => 'Santa Claus',
        2 => 'Homer Simpson',
        3 => 'Papa Smurf'
    );
    
    $location = array(
        1 => 'North Pole',
        2 => 'Springfield',
        3 => 'Smurf village'
    );
    
    foreach ($person as $id => $name)
        echo "$name live in {$location[$id]}
    ";
    
    评论
  • duanniwu7730 2013-12-07 23:29
    关注

    $partno is the key, $p is value e.g. $email->parts = array("key" => "value");

    Read this

    http://www.php.net/manual/en/control-structures.foreach.php

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Qt 不小心删除了自带的类,该怎么办
  • ¥15 我需要在PC端 开两个抖店工作台客户端.(语言-java)
  • ¥15 有没有哪位厉害的人可以用C#可视化呀
  • ¥15 可以帮我看看代码哪里错了吗
  • ¥15 设计一个成绩管理系统
  • ¥15 PCL注册的选点等函数如何取消注册
  • ¥15 问一下各位,为什么我用蓝牙直接发送模拟输入的数据,接收端显示乱码呢,米思齐软件上usb串口显示正常的字符串呢?
  • ¥15 Python爬虫程序
  • ¥15 crypto 这种的应该怎么找flag?
  • ¥15 代码已写好,求帮我指出错误,有偿!