使用 JSON 组合字符串和数组


Combine a string and an array with JSON

我正在尝试将字符串和数组与JSON组合在一起。到目前为止,没有成功。

这是PHP代码:

<?php
$url = ‘example.com’;
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = ‘testtext';
preg_match_all($regex,$data, $match);
    //var_dump($match);
    //echo  json_encode($match[1]);
$json = array($input, $match[1]);
$json_data = json_encode($json);
echo  $json_data;
?>

$match返回一个数组,例如:

"22425229","22493325","22596308","24635614","22202322"

上面只创建字符串的一个实例:

["testtext",["22425229","22493325","22596308"......

我想创建这样的东西:

"testtext":"22425229", "testtext":"22425230"

谢谢

你想做的事情是不可能的。 [ "testtext":"22425229", "testtext":"22425230" ]假设一个数组,其中每个键都是"测试文本"。不能重复具有相同键的数组或对象。

您可以做的是创建一个数组数组,其中每个项目都是一个关联数组(JSON 中的对象):

<?php
$url = 'example.com';
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = 'testtext';
preg_match_all($regex,$data, $match);
    //var_dump($match);
    //echo  json_encode($match[1]);
function outputArray( $value ) {
    global $input;
    return array( $input => $value );
}
$json = array_map( 'outputArray', $match );
$json_data = json_encode($json);
echo  $json_data;
?>

输出为:[{"testtext":"22425229"},{"testtext":"22493325"},{"testtext":"22596308"},{"testtext":"24635614"},{"testtext":"22202322"}]

我的解决方案是错误的,不应该留在这里混淆其他人......正确的解决方案可以在吉姆斯的回答中找到...