2 回答
TA贡献1828条经验 获得超3个赞
$string = '{
"my_index": 1,
"first_name": "John",
"last_name": "Smith",
"address": {
"address1": "123 Main St",
"address2": "PO Box 123",
"city": "Anywhere",
"state": "CA",
"zip": 12345
}
}';
$recursiveIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($string, true)), RecursiveIteratorIterator::SELF_FIRST);
$data = array('$data = array();');
foreach ($recursiveIterator as $key => $value) {
$currentDepth = $recursiveIterator->getDepth();
$keys = array();
// Traverse up array to get keys
for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
$keys[] = $recursiveIterator->getSubIterator($subDepth)->key();
}
if (is_array($value)) {
$data[] = '';
}
$data[] = '$data["' . implode('"]["', array_reverse($keys)) . '"] = ' . (!is_array($value) ? is_int($value) ? $value : '"' . $value . '"' : 'array()') . ';';
}
echo '<pre>';
print_r(implode("\n", $data));
echo '</pre>';
TA贡献1818条经验 获得超8个赞
与您之后的内容并非 100% 相同,但它有效地创建了一段您可以使用的 PHP 代码。主要是将其解码为PHP数组,然后用于var_export()输出结果数组。在它周围添加一些样板以提供一些代码......
$data='{
"my_index": 1,
"first_name": "John",
"last_name": "Smith",
"address": {
"address1": "123 Main St",
"address2": "PO Box 123",
"city": "Anywhere",
"state": "CA",
"zip": 12345
}
}';
echo '$data = '.var_export(json_decode($data, true), true).';';
给你
$data = array (
'my_index' => 1,
'first_name' => 'John',
'last_name' => 'Smith',
'address' =>
array (
'address1' => '123 Main St',
'address2' => 'PO Box 123',
'city' => 'Anywhere',
'state' => 'CA',
'zip' => 12345,
),
);
- 2 回答
- 0 关注
- 147 浏览
添加回答
举报