繁体   English   中英

PHP多维数组推送和循环

[英]PHP Multidimensional Array push and loop

当涉及到多维数组以及如何推送时,我在理解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');
}

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

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

$array[$strAtt] = $strVal;

然后循环数组就这样做:

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

通过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)
)

希望有所帮助,快乐编码:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM