-1

変更したいJSON文字列があります。

JSON文字列は次のようになります

string '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' (length=114)

このJSONをに変換したい

string '[{"id":"AT02708872"},{"id":"DE60232348"}]' (length=114)

だから私はドットと最後の文字を削除したいと思います。私はSymfony2(PHP)を使用しています

誰もが私がそれをどのように行うことができるかについての考えを持っています。

ありがとう

4

4 に答える 4

2

デコード、変更、再エンコード。

<?php

$json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';

// Decode the JSON data into an array of objects. 
// Symfony probably will have some JSON handling methods so you could look at
// those to keep the code more Symfony friendly.
$array = json_decode($json);


// Loop through the array of objects so you can modify the ID of 
// each object. Note the '&'. This is calling $object by reference so
// any changes within the loop will persist in the original array $array
foreach ($array as &$object)
{
    // Here we are stripping the periods (.) from the ID and then removing the last
    // character with substr()
    $object->id = substr(str_replace('.', '', $object->id), 0, -1);
}

// We can now encode $array back into JSON format
$json = json_encode($array);

var_dump($json);

おそらくSymfony2内にネイティブJSON処理があるので、それをチェックすることをお勧めします。

于 2012-10-12T14:14:50.853 に答える
0

javascript正規表現を使用して、不要な要素を空白の文字列に置き換えることができます。ただし、phpオブジェクトへの文字列を解析する前にこれを行う必要があります。

于 2012-10-12T14:06:54.187 に答える
0

一本の紐ですか?その上で正規表現を実行します。

<?
   $str =  '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' ;
   echo preg_replace('/\.[A-Z]"/','"',$str);
?>

これは、すべてのIDがで終わることを前提としています。大文字1文字。

于 2012-10-12T14:10:50.743 に答える
0
$json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';

$json = json_decode($json, true);

$result = array();
foreach($json as $item) {
    $tmp = explode('.', $item['id']);
    $result[] = array('id' => $tmp[0] . $tmp[1]);
}

$result = json_encode($result);
echo $result;
于 2012-10-12T14:15:00.600 に答える