【问题标题】:PHP Multidimensional Array push and loopPHP多维数组推送和循环
【发布时间】:2012-10-06 10:46:12
【问题描述】:

当涉及到多维数组以及如何推送时,我在理解 PHP 中的编码时遇到了一些麻烦。 这个想法是推送一个“属性”和一个“属性值”

我试过下面的公式

   $i = 0;
   $array = array();
    foreach($node as $a)
    {
        $strAtt = $node->PROP[$i]->attributes();
        $strVal = $node->PROP[$i]->PVAL;

        $output = $output.$strAtt." : ".$strVal."<BR>";
        $array[] = ($strAtt => $strVal);

$array[] = ($strAtt => $strVal); 并没有给我太大的成功。 我试过 array_push($array, $strAtt => $strVal) - 没有运气..

作为一个额外的问题,我如何循环遍历数组并打印我的多维值?。

新代码

while ($z->name === 'RECORD')
{

$node = new SimpleXMLElement($z->readOuterXML());

$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
    $strAtt = $node->PROP[$i]->attributes();
    $strVal = $node->PROP[$i]->PVAL;

    $output = $output.$strAtt." : ".$strVal."<BR>";
    $array[$strAtt] = $strVal;

    if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
    {
        $Print = TRUE;
        $Product = $node->PROP[$i]->PVAL;
    }       

    $i++;
}
if($Print == TRUE) {
    echo $output;
    echo "Product : ".$Product."<br>";
    var_dump($array);
    }

    //print_r($array);
    $print = FALSE;

// go to next <product />
$z->next('RECORD');
}

添加了新代码。出于某种原因,当我转储它时,我的 $array 完全是空的,尽管我的 $Output 充满了文本?

【问题讨论】:

  • array_push( $array, array( $strAtt =&gt; $strVal ));
  • 可以通过this answer了解数组在php中是如何工作的

标签: php loops multidimensional-array


【解决方案1】:

听起来您想要一个“关联”数组,而不一定是多维数组。对于关联数组,您不使用 array_push。只需这样做:

$array[$strAtt] = $strVal;

然后循环数组只需这样做:

foreach ($array as $key => $value) {
    echo "$key = $value\n";
}

【讨论】:

  • 我明白你的意思,但这会将下一个属性和值添加到我的数组中,还是我需要类似 $array = $array[$strAtt] = $strVal; ?
  • 没错,在循环内您可以使用$newArray[$key] = $value 之类的方式分配键和键值 - 在本例中,它会在每个循环中输出值。
  • 嗯...我添加了我的“新”代码。出于某种原因,我的数组是空的,尽管 $Output 变量中有很多文本......有什么想法吗?
  • @UlrikVadstrup,我看到了你的新代码。您在代码中的哪个位置初始化 $array 变量?您应该在 while 循环之外有一个位置,您可以在其中使用 $array = array(); 初始化数组
【解决方案2】:

通过array in php,你就会明白数组在php中是如何工作的。 此外,如果您想向多维数组添加元素,您可以这样实现:

$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
    $array [$key] = $value;
}

这将是循环后生成的$array

array (
"key1"=> array (
a,b
) , 
"key2"=> 
array (c,d)
)

希望对您有所帮助,祝您编码愉快:)

【讨论】:

  • 我认为 davidethell 是在正确的道路上。也许我正在寻找的是一个“关联”数组。我还没有解决我的添加问题 - 不过
  • @UlrikVadstrup ,顺便说一句,这也是一个关联数组:p
猜你喜欢
  • 2013-10-02
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2011-08-30
  • 2013-06-25
  • 2019-07-17
  • 2012-05-13
  • 1970-01-01
相关资源
最近更新 更多