簡體   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