首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP/MYSQL/JSON:解析复杂字符串或重组为字典

PHP/MYSQL/JSON:解析复杂字符串或重组为字典
EN

Stack Overflow用户
提问于 2018-07-09 01:23:32
回答 1查看 74关注 0票数 -1

我通过JSON接收到一个表示对象的复杂字符串:

代码语言:javascript
复制
    <Offers: 0x170483070> (entity: Offers; id: 0xd00000000b880006 <x-
coredata://03C4A684-2218-489C-9EF6-42634ED10552/Offers/p738> ; data: {\\n    
topic = nil;\\n    topid = 9403;\\n    hasserverid = nil;\\n    isprivate = nil;\\n 
   lasttouched = \\\"2018-07-08 16:49:01 +0000\\\";\\n    lastviewed = nil;\\n
    localid = 42;\\n    needpicsync = nil;\\n    needsync = nil;\\n    secondorder
 = 0;\\n    oid = 0;\\n    offer = test;\\n    offerdone = nil;\\n    offernumber =
 70;\\n    userid = 1;\\n    wasdeleted = nil;\\n    whenadded = \\\"2018-07-08
 16:04:20 +0000\\\”;\\n})

我想把某些东西保存到MYSQL中。在上面的示例中,我想将字段offer和offernumber等保存到一个记录中,如下所示:

代码语言:javascript
复制
$sql = "INSERT into offers (offer,offernumber) VALUES ('test',70)";

当然,要做到这一点,我首先必须解析字符串,以获得offer的值,offer number的值,理想情况下,还有整个对象的键和值。

我应该首先将字符串转换为某种数组、字典或数据结构吗?或者我应该尝试使用正则表达式或其他方法来解析字符串?如果是后者,希望得到有关使用什么正则表达式或技术的建议。

提前感谢您的任何建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-09 03:02:34

您可以尝试使用PHP将字符串转换为对象,这可能会对您有所帮助:

代码语言:javascript
复制
$input = "**The input string**";

// Remove the escaped new lines
$jsonString = str_replace("\\n", "\n", substr($input, strpos($input, "data: ")+5));
$jsonString = substr($jsonString, 0, strlen($jsonString) - 1);

// Convert the equals, semicolons and remove the escaped backslash
$jsonString = str_replace(";", ",", $jsonString);
$jsonString = str_replace("=", ":", $jsonString);
$jsonString = str_replace('\\', '', $jsonString);

$matches = array();

// Use regex to get json key-value
if(preg_match_all('/(\w+)\s*\:\s*(.+)\s*\,/m', $jsonString, $matches,PREG_SET_ORDER, 0)){
    // Iterate the matches and enclose key and value into double quotes
    foreach($matches as $item){
     // Enclose the value if isn't a number or a date
        if(strpos(trim($item[2]), '"') !== 0 && !is_numeric($item[2])){
            $item[2] = '"'.$item[2].'"';
        }
        // Replace in json string
        $jsonString = str_replace($item[0], '"'.$item[1].'"'.' : '.$item[2].',', $jsonString);
    }
}

// Remove last comma
$jsonString = substr($jsonString, 0, strlen($jsonString) - 3) . '}';

// Transform json string to object
$jsonObject = json_decode($jsonString);

// Show the json string
echo($jsonString);

// Display the object
var_dump($jsonObject);

上面的代码将给定的字符串转换为一个对象,然后您可以根据需要使用这些属性。

你可以在这里试试:PHP Sandbox

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51234399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档