修复"Warning: Illegal string offset" -- (但不丢失内容)



我已经为这个问题寻找了解决方案,但没有一个能解决我的问题。答案建议我在处理数组之前使用isset来检查它。但我稍后会解释它是如何不为我做的

Pre-req:
我从一次旅行中得到了一个巨大的XML文件&travel Web服务,我会解析并转换为PHP数组,然后对其进行一些操作。

我的方法:
我使用SimpleXML加载xml并将其转换为PHP数组,如下所示:

$xml = file_get_contents(APPPATH."tour.xml", true);
$xmlString = htmlentity_to_xml($xml); //custom method to clean XML
$Str = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
//converting to array
$json = json_encode($Str);
$array = json_decode($json,TRUE);

然后,我将这个数组连同搜索参数(cityName&dates)和数组本身一起发送到fitlerTours($searchParams, $tourArray)方法。

然后使用foreach(),我将在每次旅行中查找cityName,并在找到时升起一面旗帜。

问题
当我过滤旅行团(包含cityName的旅行团)的日期时,我会得到这个。

Severity: Warning
Message: Illegal string offset 'year'
Filename: controllers/tourFilter.php
Line Number: 78

还显示了设置为"month"one_answers"day"的警告
这是我的日期过滤器PHP:(第78行是第4行)

if($flag == 1){
if(!empty($fromDate)){
foreach($tour['departureDates']['date'] AS $date){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
}
else{
$dateFlag = 1;
}
$flag = 0;
}
if($dateFlag == 1){//Collect tours which contain the keyword & dates to $response array
$responseArray[] = $tour;
$dateFlag = false; //Reset Flag
}

以下是XML:的片段

...
<departureDates>
<date>
<day>7</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>Available</departureStatus>
</date>
<date>
<day>8</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>SoldOut</departureStatus>
</date>
</departureDates>
...

现在,如果我使用我通过四处搜索找到的解决方案是检查isset()是否正确设置了数组,它不会返回true,第78行没有执行,数据丢失。但我需要数据。

这种情况只发生在我搜索的关键字上
如有任何帮助,我们将不胜感激。

错误表明$date变量在某个点被检测为字符串。。。

字符串中的字符可以通过指定使用方括号,如$str[42]中所示。将字符串想象为数组用于此目的的字符数。参见此处

所以试试这个:

if(is_array($date)){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
else {
//If this is not an array what is it then?
var_dump($date);
}

最新更新