如何在PHP中打印数组数组的元素

时间:2018-02-19 17:38:10

标签: php arrays

我有这样的php数组,它是从php控制器生成的。

Array
(
  [data001] => Array
    (
      [0] => stdClass Object
        (
          [page_id] => 204725966262837
          [type] => WEBSITE01
        )

      [1] => stdClass Object
        (
          [page_id] => 163703342377960
          [type] => COMMUNITY02
        )
      )

  [data001] => Array
    (
      [0] => stdClass Object
        (
          [page_id] => 204725966000037
          [type] => WEBSITE02
        )

      [1] => stdClass Object
        (
          [page_id] => 163703342377960
          [type] => COMMUNITY02
        )
      )
)

我想在同一个foreach循环中回显这两个数组。 我试过这样但是没效果。

foreach ($results as $result) {
    echo $result->type; 
    echo "<br>";
} 

但我不想使用foreach ($results['data001'] as $result)因为我必须写两个foreach循环。

2 个答案:

答案 0 :(得分:0)

如果你有这个阵列试试这个,

<?php
// Multidimensional array
$masterArray = array(
    "0" => array(
        "page_id" => "204725966262837",
        "type" => "WEBSITE01",
    ),
    "1" => array(
        "page_id" => "163703342377960",
        "type" => "COMMUNITY02",
    ),
    "2" => array(
        "page_id" => "204725966000037",
        "type" => "WEBSITE02",
    ),
    "3" => array(
        "page_id" => "204725966000037",
        "type" => "WEBSITE02",
    )
);
// Printing all the keys and values one by one

$keys = array_keys($masterArray); 

 for($i = 0; $i < count($masterArray); $i++) {

    foreach($masterArray[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "<br>";
    }
}
?>

答案 1 :(得分:0)

这里只有一个foreach,这对你有用吗?

foreach ($results as $result) {
    for ($i=0; $i < count($result); $i++) { 
        echo $result[$i]->type; 
        echo "<br>";
    }
}