【问题标题】:How to get Key from this string array in PHP [duplicate]如何在 PHP 中从这个字符串数组中获取密钥 [重复]
【发布时间】:2022-01-11 09:40:18
【问题描述】:

数组([status] => 1 [message] => 登录成功。)

我想从这个数组中访问状态,比如字符串。 我从 API 获取此响应。 它看起来不太好。不像数组或不像 json。 我无法访问密钥,所以现在任何人都可以帮助我。

【问题讨论】:

  • 请看我的问题。 => awesomescreenshot.com/image/…
  • “我从 API 获取此响应”...然后 API 已损坏。它绝对不应该用 PHP print_r() 输出响应

标签: php


【解决方案1】:

也许您可以使用preg_match 来实现这一点?在3v4l.org 上查看它,但它不是一个非常动态的解决方案,我假设status 将始终是一个整数。

preg_match('/(\Sstatus\S => \d)/',
    'Array ( [status] => 1 [message] => Logged In Successfully. )',
    $matches
);

if(!empty($matches))
{
    $status = (int) $matches[0][strlen($matches[0]) -1]; // 1
}

【讨论】:

    【解决方案2】:

    为了改进@Jaquarh 的答案,您可以编写这个函数来帮助您使用任何所需的字符串、键和预期类型来提取值。

    我在函数中添加了一些功能,例如不介意字符串中 => 分隔符之间有多少空格,任何值类型匹配,以便它可以检索 => 之后的数字和字符串值分隔符和修剪最终字符串值。最后,如果需要,您可以选择将最终值转换为整数 - 只需在调用函数时为 $expected_val_type 参数提供一个参数。

    $my_str 是您的 API 响应字符串,$key_str 是您要从字符串中提取其值的键。

    function key_extractor($my_str, $key_str, $expected_val_type=null) {
        
        // Find match of supplied $key_str regardless of number of spaces
        // between key and value.
        preg_match("/(\[" . $key_str . "\]\s*=>\s*[\w\s]+)/", $my_str, $matches); 
       
        if (!empty($matches)) {
            // Retrieve the value that comes after `=>` in the matched
            // string and trim it.
            $value = trim(substr($matches[0], strpos($matches[0], "=>") + 2));
         
            // Cast to the desired type if supplied.
            if ($expected_val_type === 'int') {
                return ((int) $value);
            } 
    
            return $value;
        }
      
        // Nothing was found so return null.
        return NULL;
    }
    

    然后你可以像这样使用它:

    key_extractor($res, 'status', 'int');
    

    $res 是您的 API 响应字符串。

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2021-09-01
      • 2011-03-20
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 2020-02-26
      • 2011-07-27
      • 1970-01-01
      相关资源
      最近更新 更多