遍历数组的非数字索引

时间:2011-04-14 17:21:46

标签: php arrays traversal

认为我错过了一个基本概念。我想通过遍历几个不同的数据数组来生成html。它们不使用数字作为索引,因此数字循环不起作用。我无法弄清楚如何在这里使用foreach()。当索引不是数字时,如何遍历$price$description

样品:

$traverser= 0;
while($traverser < $number_of_records)
{
    print $traverser . " - " . $price[$traverser] . "<br />";
    print $description[$traverser];
    $traverser++;
}

阵列结构的部分样本:

object(phpQueryObject)#2799 (13) { ["documentID"]=>  string(32) "1d62be942498df890cab4ccb78a007a2" ["document"]=>  &object(DOMDocument)#3 (0) { } ["charset"]=>  &string(5) "utf-8" ["documentWrapper"]=>  &object(DOMDocumentWrapper)#2 (17) { ["document"]=>  &object(DOMDocument)#3 (0) { } ["id"]=>  string(32) "1d62be942498df890cab4ccb78a007a2" ["contentType"]=>  string(9) "text/html" ["xpath"]=>  &object(DOMXPath)#4 (0) { } ["uuid"]=>  int(0) ["data"]=>  array(0) { } ["dataNodes"]=>  array(0) { } ["events"]=>  array(0) { } ["eventsNodes"]=>  array(0) { } ["eventsGlobal"]=>  array(0) { } ["frames"]=>  array(0) { } ["root"]=>  &object(DOMElement)#5 (0) { } ["isDocumentFragment"]=>  &bool(true) ["isXML"]=>  bool(false) ["isXHTML"]=>  bool(false) ["isHTML"]=>  bool(true) ["charset"]=>  &string(5) "utf-8" } ["xpath"]=>  &object(DOMXPath)#4 (0) { } ["elements"]=>  array(560) { [0]=>  object(DOMElement)#2239 (0) { } [1]=>  object(DOMElement)#2240 (0) { } [2]=>  object(DOMElement)#2241 (0) { } [3]=>  object(DOMElement)#2242 (0) { } [4]=>  object(DOMElement)#2243 (0) { } [5]=>  object(DOMElement)#2244 (0) { } [6]=>  object(DOMElement)#2245 (0) { } [7]=>  object(DOMElement)#2246 (0) { } [8]=>  object(DOMElement)#2247 (0) { }

3 个答案:

答案 0 :(得分:2)

由于您看起来也需要数组键,因为您引用了多个不同的数组,所以需要$a as $k => $v的{​​{1}}语法:

foreach

答案 1 :(得分:1)

您可以take your pic了解如何迭代它们:

<?php

  $ary = array(   // demo array
    'apple' => 'Apple',
    'orange' => 'Orange',
    'grape' => 'Grape'
  );

  // show the structure
  var_dump($ary); echo "\r\n";

  // use a foreach with the key and value
  foreach ($ary as $key => $val)
    printf("%s => %s\r\n", $key, $val);
  echo "\r\n";

  // just get the raw keys
  $keys = array_keys($ary);
  var_dump($keys); echo "\r\n";

输出:

array(3) {
  ["apple"]=>
  string(5) "Apple"
  ["orange"]=>
  string(6) "Orange"
  ["grape"]=>
  string(5) "Grape"
}

apple => Apple
orange => Orange
grape => Grape

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "orange"
  [2]=>
  string(5) "grape"
}

始终有array_map&amp; array_walk

答案 2 :(得分:0)

我不确定我是否得到了这个问题,但它真的很简单:

<?php
$array = array('foo', 'bar');
foreach ($array as $element) {
    echo "{$element}\n";
}

这应输出“foo”和“bar”。