dougou6727 2015-12-03 14:24
浏览 65
已采纳

在Array中搜索特定值

I have an issue with an array being returned from an API request which i want to search for a specific value and perform a certain operation for but i have been unsucessful in making it work. I have used array_search() function and done several things based on reading similar questions here and online but still no luck. Anyone know what i am doing wrong?

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

print_r($responses) displays:

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
)

and this is what i currently have in my code for array search

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

The result i get from:

   print_r(file_get_contents($url));

is

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

Please I am not trying to explode any array value I am trying to search for a string in the array and perform an operation as per my if statement.

Thanks

  • 写回答

2条回答 默认 最新

  • dongpobo6009 2015-12-03 15:18
    关注

    As we found out in the comments your value error_code=101 is 30 characters long and probably has some spaces at the end, so that's why it doesn't match.

    Now you either can remove these spaces when you explode it into an array, e.g.

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

    Or you remove them for each element, e.g.

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

    Also I would recommend you to check for:

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

    Since the key of the value also could be 0, which would result in not entering the if statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?