猿问

将 JSON 字符串转换为 PHP 代码块

有没有一种优雅的方式来转换这个 JSON 字符串:


{

  "my_index": 1,

  "first_name": "John",

  "last_name": "Smith",

  "address": {

    "address1": "123 Main St",

    "address2": "PO Box 123",

    "city": "Anywhere",

    "state": "CA",

    "zip": 12345

  }

}

到这个 PHP 代码块:


$data = array();

$data["my_index"] = 1;

$data["first_name"] = "John";

$data["last_name"] = "Smith";


$data["address"] = array();

$data["address"]["address1"] = "123 Main St";

$data["address"]["address2"] = "PO Box 123";

$data["address"]["city"] = "Anywhere";

$data["address"]["state"] = "CA";

$data["address"]["zip"] = 12345;

基本上,构建代码以粘贴到其他内容中。我不想要一个 json_decode() 的对象。我真的想以一串 PHP 代码结束,而不是一个 PHP 对象!


杨魅力
浏览 148回答 2
2回答

倚天杖

$string = '{&nbsp; &nbsp; "my_index": 1,&nbsp; &nbsp; "first_name": "John",&nbsp; &nbsp; "last_name": "Smith",&nbsp; &nbsp; "address": {&nbsp; &nbsp; &nbsp; &nbsp; "address1": "123 Main St",&nbsp; &nbsp; &nbsp; &nbsp; "address2": "PO Box 123",&nbsp; &nbsp; &nbsp; &nbsp; "city": "Anywhere",&nbsp; &nbsp; &nbsp; &nbsp; "state": "CA",&nbsp; &nbsp; &nbsp; &nbsp; "zip": 12345&nbsp; &nbsp; }}';$recursiveIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($string, true)), RecursiveIteratorIterator::SELF_FIRST);$data = array('$data = array();');foreach ($recursiveIterator as $key => $value) {&nbsp; &nbsp; $currentDepth = $recursiveIterator->getDepth();&nbsp; &nbsp; $keys = array();&nbsp; &nbsp; // Traverse up array to get keys&nbsp; &nbsp; for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {&nbsp; &nbsp; &nbsp; &nbsp; $keys[] = $recursiveIterator->getSubIterator($subDepth)->key();&nbsp; &nbsp; }&nbsp; &nbsp; if (is_array($value)) {&nbsp; &nbsp; &nbsp; &nbsp; $data[] = '';&nbsp; &nbsp; }&nbsp; &nbsp; $data[] = '$data["' . implode('"]["', array_reverse($keys)) . '"] = ' . (!is_array($value) ? is_int($value) ? $value : '"' . $value . '"' : 'array()') . ';';}echo '<pre>';print_r(implode("\n", $data));echo '</pre>';

弑天下

与您之后的内容并非 100% 相同,但它有效地创建了一段您可以使用的 PHP 代码。主要是将其解码为PHP数组,然后用于var_export()输出结果数组。在它周围添加一些样板以提供一些代码......$data='{&nbsp; "my_index": 1,&nbsp; "first_name": "John",&nbsp; "last_name": "Smith",&nbsp; "address": {&nbsp; &nbsp; "address1": "123 Main St",&nbsp; &nbsp; "address2": "PO Box 123",&nbsp; &nbsp; "city": "Anywhere",&nbsp; &nbsp; "state": "CA",&nbsp; &nbsp; "zip": 12345&nbsp; }}';echo '$data = '.var_export(json_decode($data, true), true).';';给你$data = array (&nbsp; 'my_index' => 1,&nbsp; 'first_name' => 'John',&nbsp; 'last_name' => 'Smith',&nbsp; 'address' =>&nbsp;&nbsp; array (&nbsp; &nbsp; 'address1' => '123 Main St',&nbsp; &nbsp; 'address2' => 'PO Box 123',&nbsp; &nbsp; 'city' => 'Anywhere',&nbsp; &nbsp; 'state' => 'CA',&nbsp; &nbsp; 'zip' => 12345,&nbsp; ),);
随时随地看视频慕课网APP
我要回答