PHP如何在知道密钥的情况下从json字符串中提取信息


PHP how to extract info from json string wtihout knowing the keys

我正在查询一项服务,是否有人有电话号码(也可能没有)。我有一个json字符串(作为返回值),如下所示:

$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';

我将此字符串转换为json_decode()函数。

$jd = json_decode($json);

然后我想只将电话号码放入一个没有密钥的数组中。

if($jd->found) {
    $o2a = get_object_vars($json);
}
var_dump($o2a);

当我想看看$o2avar_dump()函数的关系时,我得到了以下内容:

array (size=2)
    'data' => 
        array (size=2)
            0 => 
                object(stdClass)[2]
                public 'tel1' => string '1219' (length=4)
            1 => 
                object(stdClass)[3]
                public 'tel2' => string '2710' (length=4)
    'found' => boolean true

我只想把电话号码放在最后的数组中,比如:

$phones = array('1219', '2710');

让我停止这样做的是,我不知道一个人能有多少电话号码。Json数组可以由或多或少的元素组成。

$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found

它可能会改变0-到-n,所以如果它是一个常数,我可以在循环中创建该数组。

一些没有任何代码的函数:)

$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);

将其转换为数组,然后您应该能够轻松地迭代

$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
    foreach($jd['data'] as $key => $val) $phones[] = $val;
}
  • 不使用对象进行处理,而是使用json_decode函数的第二个参数,这样它就会返回一个数组
  • 检查datafound密钥是否存在
  • 由于您不知道密钥名称,因此可以使用array_values
  • Demo

$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
  $telArr = $jd['data'];
  $phones = array();
  foreach($telArr as $tel){
    $value = array_values($tel);
    $phones[] = $value[0];
  }
  var_dump($phones);
}

输出:

array(2) {
  [0]=>
  string(4) "1102"
  [1]=>
  string(4) "3220"
}

好吧,我会尝试这样的东西:

$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
    foreach ($jd->data as $key -> $value) {
        $phones[] = $value;
    }
}

尝试使用in_array和简单的foreach循环

$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
    foreach ($arr['data'] as $key => $value) {
        foreach($value as $k => $v)
            $result[] = $v;
    }
}
print_r($result);

Fiddle