从嵌套数组中的对象中仅检索某些值?

时间:2013-12-05 21:46:21

标签: php arrays object

好的我有以下数组:

array(2) {
  ["campaigns"]=>
  array(50) {
    [0]=>
    object(Campaign)#2122 (48) {
      ["name"]=>
      string(26) "FOO"
      ["id"]=>
      string(74) "****************"
      ["link"]=>
      string(44) "/ws/"
      ["status"]=>
      string(4) "Sent"
      ["lists"]=>
      array(0) {
      }
      ["fromAddress"]=>
      string(0) ""
      ["replyAddress"]=>
      string(0) ""
      ["archiveStatus"]=>
      string(0) ""
      ["archiveUrl"]=>
      string(0) ""
      ["urls"]=>
      array(0) {
      }
    }
    [1]=>
    object(Campaign)#2122 (48) {
      ["name"]=>
      string(26) "FOO"
      ["id"]=>
      string(74) "****************"
      ["link"]=>
      string(44) "/ws/"
      ["status"]=>
      string(4) "Sent"
      ["lists"]=>
      array(0) {
      }
      ["fromAddress"]=>
      string(0) ""
      ["replyAddress"]=>
      string(0) ""
      ["archiveStatus"]=>
      string(0) ""
      ["archiveUrl"]=>
      string(0) ""
      ["urls"]=>
      array(0) {
      }
    }
    [2]=>
    object(Campaign)#2122 (48) {
      ["name"]=>
      string(26) "FOO"
      ["id"]=>
      string(74) "****************"
      ["link"]=>
      string(44) "/ws/"
      ["status"]=>
      string(4) "Sent"
      ["lists"]=>
      array(0) {
      }
      ["fromAddress"]=>
      string(0) ""
      ["replyAddress"]=>
      string(0) ""
      ["archiveStatus"]=>
      string(0) ""
      ["archiveUrl"]=>
      string(0) ""
      ["urls"]=>
      array(0) {
      }
    }
  }
}

我正在使用它遍历它并回显所有对象内容:

    foreach ($getallCampaigns as $tableName => $tableData) { // Loop outer array
  foreach ($tableData as $row) { // Loop table rows
    $cols = $vals = array();
    foreach ($row as $col => $val) { // Loop this row
      $cols[] = $col;
      $vals[] = $val; // You may need to escape this before using it in a query...
      echo '<li>'.$col.': '. $val .'</li>';
    }
  }
}

我的问题是如何只打印['name']和['id']而不是整个对象?

1 个答案:

答案 0 :(得分:1)

如果您只希望获得两个属性,则不需要整个最内层循环。它正在做的是通过foreach迭代对象属性并将它们全部写出来。它是您要迭代的对象,因此请使用->并仅使用您需要的属性。

foreach ($getallCampaigns as $tableName => $tableData) { // Loop outer array
  foreach ($tableData as $row) { // Loop table rows
    // The entire inner loop is unneeded.
    // Use htmlspecialchars() to escape as HTML output, always recommended
    echo '<li>Name:' . htmlspecialchars($row->name) . '</li><li>ID: ' . htmlspecialchars($row->id) . '</li>';
  }
}