如何在特定索引的数组值前呼应文本标签。

问题描述 投票:0回答:1

我写了下面的PHP代码,我想生成一个类似的表格,如截图所示。

该表也应该有类似的标题 Job:Email: 在工作名称和电子邮件地址之前。谢谢

<?php

$company = array
  (

  array("John Smith","Accountant","[email protected]", 70),
  array("May Black","Business Analyst","[email protected]", 40),
  array("Tom white","Plummer","tomwhite@example", 30),
  array("Susan Kim","Engineer","[email protected]", 80)

  );

  echo "--Customer List-- <br> <br>";

  for($i = 0; $i < 4; $i++) {
      for($j = 0; $j < 3; $j++) {
        echo $company[$i][$j]."<br>";  

      }
      echo "<br><br>";
  }

?>

enter image description here

php arrays for-loop label echo
1个回答
0
投票

如果变量 $j 是1或2,在数组值之前打印出你的前缀文本?

// Inner for-loop
for($j = 0; $j < 3; $j++) {

  // Additional text when it's a (1) job, or (2) email
  if($j == 1) echo 'Job: ';
  if($j == 2) echo 'Email: ';

  echo $company[$i][$j]."<br>";
}

0
投票

你也可以为标题定义一个数组,然后(有条件地)先呼应这些标题(如果它们不是空字符串)。注意,我使用了一个 foreach 循环,以避免调查数组中有多少员工。我仍然保留了内部循环([0-3))来不显示敏感的年龄信息(尽管可以用不同的方式来控制)。

<?php
  $company = array(
    array("John Smith", "Accountant", "[email protected]", 70),
    array("May Black", "Business Analyst", "[email protected]", 40),
    array("Tom white", "Plummer", "tomwhite@example", 30),
    array("Susan Kim", "Engineer", "[email protected]", 80)
  );

  $title = array("", "Job", "Email", "Age");

  echo "--Customer List--<br><br>\n";

  foreach($company as $employee) {
    for($j = 0; $j < 3; $j++) {
      if($title[$j]) echo $title[$j] . ": ";
      echo $employee[$j] . "<br>";
    }
    echo "<br><br>\n";
  }
?>

如果您想从一个地方控制员工的显示方式,另一个选项可以很方便。通过创建一个 class 和一个成员函数来显示(适当的)信息,当你想改变雇员信息在所有被调用的地方的显示方式时,你只需要改变显示函数。它还增加了其他的优点,比如让处理某一类型对象的代码与定义该类型的代码保持紧密联系。

<?php
    class Employee {
        public $Name;
        public $Job;
        protected $Email;
        private $Age;

        public function __construct($n, $j, $e, $a) {
            $this->Name = $n;
            $this->Job = $j;
            $this->Email = $e;
            $this->Age = $a;
        }

        public function display($delim = "<br>") {
            echo $this->Name . $delim;
            echo "Job: " . $this->Job . $delim;
            echo "Email: " . $this->Email . $delim;
            echo $delim . $delim;
            echo "\n";
        }
    }

    $employees = array(
        new Employee("John Smith","Accountant","[email protected]", 70),
        new Employee("May Black","Business Analyst","[email protected]", 40),
        new Employee("Tom white","Plummer","tomwhite@example", 30),
        new Employee("Susan Kim","Engineer","[email protected]", 80)
    );

    echo "--Customer List--<br><br>\n";
    foreach($employees as $employee) {
        $employee->display();
    }
?>
© www.soinside.com 2019 - 2024. All rights reserved.