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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证