2015-12-03 150 views
0

具体数值我有我要搜索一个特定值并执行特定操作的API请求返回一个数组的问题,但我一直在做它的工作不成功的。我已经使用array_search()函数,并根据在这里和在线阅读类似的问题做了几件事情,但仍然没有运气。任何人都知道我做错了什么?搜索阵列

$responses = explode("\n", file_get_contents($url)); 
print_r($responses); 

的print_r($回应)显示:

Array 
(
[0] => destination_msisdn=233887 
[1] => country= 
[2] => countryid= 
[3] => operator= 
[4] => operatorid= 
[5] => authentication_key=XXXXXX 
[6] => error_code=101 
[7] => error_txt=Destination MSISDN out of range 
) 

,这就是我目前在我的代码为阵列搜索

if(array_search("error_code=101", $responses)){ 
    echo "Incorrect!"; 
} 

结果我从获得:

print_r(file_get_contents($url)); 

destination_msisdn=23345678 country= countryid= operator= operatorid= authentication_key=XXXXX error_code=101 error_txt=Destination MSISDN out of range 

请不要试图炸开任何数组值我试图在数组中搜索一个字符串并根据我的if语句执行操作。

谢谢

+0

您可以将'print_r(file_get_contents($ url));'的结果添加到您的问题中吗? – KhorneHoly

+0

问题是什么? – Rizier123

+0

@ Rizier123问题是我想在if语句不回显 – Unicornese

回答

2

正如我们在评论你的价值error_code=101是30个字符长,并有可能在年底一些空间发现了,所以这就是为什么它不匹配。

现在,您可以在将它分解为数组时将其移除,例如,

$responses = preg_split("/\s*\n\s*/", file_get_contents($url)); 

或者您为每个元素删除它们,例如,

$responses = array_map("trim", $responses); 

此外,我建议你检查:

array_search("error_code=101", $responses) !== FALSE 

因为该值的键也可以是0,这将导致不能进入if语句。

-1

从您的代码为我工作的事实开始。

你可以试着改为爆炸数组,像这样搜索字符串?

if(strpos(file_get_contents($url),"error_code=101") !== FALSE) 
    echo "Incorrect!"; 

[编辑]

+0

问题在于,从file_get_contents($ url)返回的内容不是字符串,而是数组,因此会出错。 – Unicornese

+0

但你做_explode(“\ n”,file_get_contents($ url)); _ explode接受一个字符串作为第二个参数。 –