如何在foreach循环中打印一个值?

时间:2013-06-28 23:09:50

标签: php

$id = 123;

$my_var[$id]["lname"] = "Smith";
$my_var[$id]["fname"] = "John";

foreach ($my_var as $rec) {
    print "Last Name: " . $rec["lname"]. "\n";
    print "First Name: " . $rec["fname"]. "\n";

    // print "ID: " . $id . "\n";      // THIS WORKS BUT NOT WHAT I WANT
    print "ID: " . $rec[$id] . "\n";     // DOESNOT WORK
}

如何在foreach()循环中打印$ id的值而不直接使用$ id?

2 个答案:

答案 0 :(得分:3)

foreach循环中指定键和值。我在这里称之为$key,因为您已使用$id,但您也可以回收该名称。

foreach ($my_var as $key => $rec)
{
   print "Last Name: " . $rec["lname"]. "\n";
   print "First Name: " . $rec["fname"]. "\n";

   print "ID: " . $key . "\n";   
}

答案 1 :(得分:3)

在PHP中,您可以按照以下方式访问关联数组中的键:

$id = 123;

$my_var[$id]["lname"] = "Smith";
$my_var[$id]["fname"] = "John";

foreach ($my_var as $key => $rec) {
    print "Last Name: " . $rec["lname"]. "\n";
    print "First Name: " . $rec["fname"]. "\n";

    print "ID: " . $key . "\n";     // Is your ID
}