duangao7133 2013-02-13 14:06
浏览 73
已采纳

嵌套foreach中的两个对象数组

I have two variables:

  • $foo - client1, client2, client3 (an object array)
  • $bar - name, id, turnover (a string array)

If I echo $foo->name of client 1 it returns successful value, but:

foreach ($foo as $key1 => $value1) {

  foreach ($bar as $key2 => $value2) {

    echo $value2->$value1; // THIS IS NOT WORKING

  }

}

Hope I'm clear; I want to return these values:

client1's name
client1's id
client1's turnover
client2's name 
client2's id
etc...

This is successful:

foreach($foo as $client) {

  echo $client->name."<br>";
  echo $client->id."<br>";
  echo $client->billable."<br>";

}

returns client name, his id and if he's billable or not for every client. But the above code is not working. Name, id and billable are stored in a string thus:

$bar = array ([0] => name, [1] => id, [2] => billable )
  • 写回答

3条回答 默认 最新

  • doumeng3188 2013-02-13 14:20
    关注

    You need to replace

    $value2->$value1
    

    With

    $value1->$value2
    

    If i understand you correctly example

    $bar = array("name", "id", "turnover");
    $foo = array(
            (object) array_combine($bar,range(1,3)),    //client 1
            (object) array_combine($bar,range("A","C")),    //client 2
            (object) array_combine($bar,range("X","Z")),    //client 3
    );
    
    
    
    foreach ($foo as $key1 => $value1) {
        foreach ($bar as $key2 => $value2) {
            echo "Clients $key1 $value2 = ",$value1->$value2 ,PHP_EOL; // THIS IS NOT WORKING
        }
        echo PHP_EOL ;
    }
    

    Output

    Clients 0 name = 1
    Clients 0 id = 2
    Clients 0 turnover = 3
    
    Clients 1 name = A
    Clients 1 id = B
    Clients 1 turnover = C
    
    Clients 2 name = X
    Clients 2 id = Y
    Clients 2 turnover = Z
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了