我该怎么回应这个数组呢?

时间:2015-05-15 02:59:39

标签: php arrays

我不知道如何抓取变量中的数据并将其放入foreach循环中。

class Tree{
  private $info = array(
    array('name'=>'Jim','state'=>'NU','company'=>'NU','phone'=>array('cell'=>'5615111111','office'=>'5611111111'),'email'=>array('primary'=>'exs@example.com','ex@there.com')),
    array('name'=>'Joe Smith','city'=>'Phoenix','phone'=>'4805551111','email'=>'jsmith@some_email.com'),
    array('name'=>'John Doe','city'=>'Chandler','company'=>'Doe Co.','email'=>array('jdoe@gmail.com','personal'=>'email@email.com'),'phone'=>'6025550002')
  );
}

3 个答案:

答案 0 :(得分:1)

假设您在同一个班级中使用该变量,则可以执行此操作。

$arrVal = array();
$arrVal  = $info;

foreach ($arrVal as $val)
{
   foreach($val as $sing)
   {
     //access the value of each array with index. Eg: $sing['name']

   }

}

我希望这有助于你

答案 1 :(得分:1)

如果您在课堂内,可以使用$this->variableName访问您的私人变量。例如,如果在__construct方法中使用它,则可以回显所有这些名称:

假设您有一个名为Class.Tree.php的文件:

class Tree{
  private $info = array(
    array('name'=>'Jim','state'=>'NU','company'=>'NU','phone'=>array('cell'=>'5615111111','office'=>'5611111111'),'email'=>array('primary'=>'exs@example.com','ex@there.com')),
    array('name'=>'Joe Smith','city'=>'Phoenix','phone'=>'4805551111','email'=>'jsmith@some_email.com'),
    array('name'=>'John Doe','city'=>'Chandler','company'=>'Doe Co.','email'=>array('jdoe@gmail.com','personal'=>'email@email.com'),'phone'=>'6025550002')
  );
  public function __construct() {
    // Leaving this in for references' sake
    /* foreach ($this->info as $elm) {
     *   echo $elm["name"] . "<br/>";
     * }
     **/
  }
  public function getInfo() {
    return $this->info;
  }
}

现在在您的视图(正文)中,您可以使用以下内容:

<?php 
  // Watch this line that you really have a file called Class.Tree.php in the same directory!
  require_once 'Class.Tree.php';
  $tree = new Tree();
  $info = $tree->getInfo();
?>
<table>
  <tr>
    <th>Name</th>
    <th>State</th>
    <th>City</th>
    <th>Phone</th>
  </tr>
  <?php foreach ($info as $elm) { ?>
    <tr>
      <td><?php echo (isset($elm['name'])) ? $elm['name'] : ""; ?></td>
      <td><?php echo (isset($elm['state'])) ? $elm['state'] : ""; ?></td>
      <td><?php echo (isset($elm['city'])) ? $elm['city'] : ""; ?></td>
      <td>
        <?php if (isset($elm['phone'])) {
          if (is_array($elm['phone'])) {
            foreach ($elm['phone'] as $key => $phone) {
              echo $phone . " ($key)<br/>";
            } 
          } else { 
            echo $elm['phone'];
          }
        } ?>
      </td>

    </tr>
  <?php } ?>
</table>

答案 2 :(得分:0)

public function show() {
    foreach ($this->info as $node) {
        foreach ($node as $key => $value) {
            echo "key = " . $key . ", value = " . $value . PHP_EOL; // $value may be Array
        }
    }
}
相关问题