简体   繁体   中英

PHP Multidimensional Array push and loop

I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push. The idea is to push a "Attribute" and a "Attribute value"

I have tried the formula below

   $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);

The $array[] = ($strAtt => $strVal); doesnt give me much success. I have tried array_push($array, $strAtt => $strVal) - no luck..

As an extra questions, how do I loop trough the array and print me multidimensional values ?.

NEW CODE

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');
}

New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?

It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:

$array[$strAtt] = $strVal;

Then to loop the array just do this:

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

Go through array in php , you will understand how array works in php. Besides if you want to add an element to a multidimensional array you can achieve like this :

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

This will be the resulting $array after the loop :

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

Hope that helps , happy coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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