0

我有两个变量:

  • $foo - client1, client2, client3 (一个对象数组)
  • $bar - 名称、id、营业额(字符串数组)

如果我回显$foo->name客户端 1,它会返回成功值,但是:

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

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

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

  }

}

希望我很清楚;我想返回这些值:

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

这是成功的:

foreach($foo as $client) {

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

}

返回客户姓名、他的 ID 以及他是否可以为每个客户计费。但是上面的代码不起作用。名称、id 和 billable 存储在一个字符串中,因此:

$bar = array ([0] => name, [1] => id, [2] => billable )
4

3 回答 3

3

为变量赋予有意义的名称,并使用花括号访问:

foreach ($clients as $i => $client) {

  foreach ($keys as $j => $key) {

    echo $client->{$key};

  }

}
于 2013-02-13T14:09:44.707 回答
1

这是有效的:

$foo = array( "client1", "client2", "client3"); 
$bar = array("name","id", "turnover");

foreach ($foo as  $value1) {
    foreach ($bar as $value2) {
        echo $value1 . "->" . $value2 . "\n";
    }
}

http://sandbox.onlinephpfunctions.com/code/ebdba5ef40498d4ead4be9a281f715565717471a

我不知道你的问题出在哪里,我猜是错字。你没有写出你的输出,你的代码是半伪代码(例如连接你不使用的两个值->)。您应该提供更多详细信息和更准确的代码。

于 2013-02-13T14:12:02.697 回答
1

你需要更换

$value2->$value1

$value1->$value2

如果我正确理解你的例子

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

输出

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
于 2013-02-13T14:20:56.243 回答