php中数组元素的数量

时间:2014-06-15 18:00:56

标签: php arrays

我试图在数组中显示没有元素,但在我尝试打印计数时它显示为1

<?php
if(!$xml=simplexml_load_file('sunglasses.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
$array1=array();
foreach($xml as $syn)
{
for($i=0;$i<count($syn->productId);$i++)
{
$array1=$syn->productId;

}

}
echo count($array1, COUNT_RECURSIVE);
?>

xml文件中有10个产品。所以我希望计数为10,但其打印仅为1。 请告诉我代码中有什么不对。

2 个答案:

答案 0 :(得分:0)

您的代码格式很糟糕。

是的,xml中可能有10个元素,但$array1中只有一个元素,因为只有最后一个赋值存在。尽管您将其声明为数组,但您从未告诉$array1将值推送到数组中。如果明确未通过=array_push()语法调用,则分配流程[]不会推送值。

$array1[] = $syn->productId;

应该工作。

您应该至少测试过结果。 var_dump() $array1只会给你一个值的结果 - 最后一个值,你就能理解出错了。

答案 1 :(得分:-1)

以下代码更改将解决您的问题。

  <?php
    if(!$xml=simplexml_load_file('sunglasses.xml')){
    trigger_error('Error reading XML file',E_USER_ERROR);
    }
    $array1=array();
    foreach($xml as $syn)
    {
    for($i=0;$i<count($syn->productId);$i++)
    {
   // here need to add the result in array. not to assign value directly to array object.
    $array1[] = $syn->productId;

    }

    }
    echo count($array1, COUNT_RECURSIVE);
    ?>