简体   繁体   English

PHP多维数组推送和循环

[英]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. 当涉及到多维数组以及如何推送时,我在理解PHP中的编码时遇到了一些麻烦。 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); $ array [] =($ strAtt => $ strVal); doesnt give me much success. 并没有给我很大的成功。 I have tried array_push($array, $strAtt => $strVal) - no luck.. 我试过array_push($ array,$ strAtt => $ strVal) - 没有运气..

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 ? 出于某种原因,当我转储它时,我的$数组是完全空的,虽然我的$ Output充满了文本?

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. 对于关联数组,不要使用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. 通过php中的数组 ,您将了解数组如何在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

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

Hope that helps , happy coding :) 希望有所帮助,快乐编码:)

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

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