如何区分数组和非数组输出

时间:2015-05-21 02:48:50

标签: php

我正在研究从查询中提取文件列表的方法,并且当查询返回多个文件时遇到问题。

<?php 

error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);


static $fileCount = 0;
date_default_timezone_set('UTC');

ob_start(); 


        $soapClient = new SoapClient("https://ip_address:8443/CDRonDemandService/services/CDRonDemand?wsdl", 
array("login" => "login","password"=> "password","trace" => true, "cache_wsdl" => WSDL_CACHE_NONE)); 

        echo '<pre>';   

//THIS LINE IS FOR A MANUAL PULL OF THE LIST.  ENTER THE START AND END DATES AS NEEDED

        $data = $soapClient->get_file_list("beginning_range","end_range","1");

//If $data only contains one object, execute this;

    if (count($data) === 1)
        {
        var_dump($data);
        $name = $data->FileName;
        echo '<tr><td>'. $name .'</td></tr>';
        $fileCount = '1';
        }

//Otherwise, execute this if $data contains any other number 
    else
        {
        sort($data->FileName);
        var_dump($data);
        foreach($data->FileName as $name)
                    {
                    echo '<tr><td>' . $name . '</td></tr><br>'; 
                    $fileCount++; 
                    }
        }

echo "<TABLE>";
$content = ob_get_clean();
echo "Number of CDR Files <b>" . $fileCount . "</b><br />";
echo $content;


?>

当查询的输出包含单个文件时,此代码可以正常工作。这是输出;

object(stdClass)#2 (1) {
  ["FileName"]=>
  string(40) "file_1"
}
file_1

但是当输出包含多个文件(数组)时,这就是输出;

object(stdClass)#2 (1) {
  ["FileName"]=>
  array(2) {
    [0]=>
    string(40) "file_1"
    [1]=>
    string(40) "file_2"
  }
}


Notice:  Array to string conversion in /var/www/test.php on line 49

Array

如果我删除if语句中的代码并只在else语句中保留代码,我就可以提取文件列表;

object(stdClass)#2 (1) {
  ["FileName"]=>
  array(2) {
    [0]=>
    string(40) "file_1"
    [1]=>
    string(40) "file_2"
  }
}
file_1
file_2

在我看来,If / Else结构不对,但我不确定如何纠正它。此外,var_dump语句仅用于故障排除,以显示我实际上是在提取信息,我将在以后删除它。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

如果你改变了

,也许它会奏效
if (count($data) === 1)

if (count($data->Filename) === 1)

答案 1 :(得分:1)

看起来count($data)总是等于1.您尝试使用$data->FileName访问数组。哪个是错误

if (count($data)) {
    if(is_array($data->FileName)) {
        foreach($data->FileName as $name) {
            echo '<tr><td>' . $name . '</td></tr><br>'; 
            $fileCount++;
        }
    } else {
        echo '<tr><td>'. $data->FileName .'</td></tr>';
        $fileCount++;
    }
} else {
    echo "no files!";
}

答案 2 :(得分:1)

改变这个:

if (count($data) === 1) { ... }

到此:

if ( is_array($data->Filename) ) { ... }

documentation