将perl关联数组转换为JSON并在PHP中读取

将perl关联数组转换为JSON并在PHP中读取,php,perl,Php,Perl,我正在尝试读取PHP脚本中的perl关联数组。为此,我首先尝试使用JSON模块将perl哈希转换为JSON 下面是我用来将关联数组转换为JSON的perl脚本。文件toc.pl具有关联数组“asc\u array” asc_数组看起来像 %asc_array = ( "1" => 'Introduction', "1.1" => 'Scope', "1.2" => 'Purpose',

我正在尝试读取PHP脚本中的perl关联数组。为此,我首先尝试使用JSON模块将perl哈希转换为JSON

下面是我用来将关联数组转换为JSON的perl脚本。文件toc.pl具有关联数组“asc\u array”

asc_数组看起来像

%asc_array  = (
    "1"            => 'Introduction',
    "1.1"          => 'Scope',
    "1.2"          => 'Purpose',
    "2"            => 'Terminology',
    "2.1"          => 'Definitions',
    "2.2"          => 'Service Primitives',
    "2.3"          => 'Abbreviations',
    "2.4"          => 'Acronyms',
);
这里我面临一个问题,那就是在将其转换为JSON之后,关联数组元素的顺序会发生变化

所以我的问题是,即使在将元素转换为JSON之后,如何保持元素的顺序

在将其转换为JSON之后,我正在阅读PHP脚本中的JSON

有没有更好的方法读取PHP脚本中的perl关联数组?

用于对键进行排序

use JSON;

my %asc_array = (
    "1"   => 'Introduction',
    "1.1" => 'Scope',
    "1.2" => 'Purpose',
    "2"   => 'Terminology',
    "2.1" => 'Definitions',
    "2.2" => 'Service Primitives',
    "2.3" => 'Abbreviations',
    "2.4" => 'Acronyms',
);

print JSON->new->canonical(1)->encode( \%asc_array ), "\n";
输出:

{"1":"Introduction","1.1":"Scope","1.2":"Purpose","2":"Terminology","2.1":"Definitions","2.2":"Service Primitives","2.3":"Abbreviations","2.4":"Acronyms"}
Array
(
    [1] => Introduction
    [1.1] => Scope
    [1.2] => Purpose
    [2] => Terminology
    [2.1] => Definitions
    [2.2] => Service Primitives
    [2.3] => Abbreviations
    [2.4] => Acronyms
)

既然散列键很容易排序,为什么不在PHP脚本接收到数据后对其进行排序呢

i、 e

然后,在PHP脚本中:

# replace this with whatever method you're using to get your JSON
# I've jumbled up the order to demonstrate the power of sorting.
$json = '{"2.3":"Abbreviations", "2.1":"Definitions", "1":"Introduction", "2.4":"Acronyms", "1.1":"Scope", "2":"Terminology", "2.2":"Service Primitives", "1.2":"Purpose"}';

$decoded = json_decode( $json, true );
ksort($decoded);

print_r($decoded);
输出:

{"1":"Introduction","1.1":"Scope","1.2":"Purpose","2":"Terminology","2.1":"Definitions","2.2":"Service Primitives","2.3":"Abbreviations","2.4":"Acronyms"}
Array
(
    [1] => Introduction
    [1.1] => Scope
    [1.2] => Purpose
    [2] => Terminology
    [2.1] => Definitions
    [2.2] => Service Primitives
    [2.3] => Abbreviations
    [2.4] => Acronyms
)

关联数组(哈希)没有任何顺序。为什么要有特定的顺序?所以,您不能依赖哈希键顺序,也不能依赖javascript对象属性顺序。改用数组。@M42:我正在存储目录,节号作为键,标题作为值。为此,我使用了perl关联数组。在perl中循环时,它是有序的,但是在转换为JSON之后,顺序改变了。那么,您建议如何解决上述问题呢?您在阅读哪些Perl资源时使用了术语“关联数组”?自从二十年前Perl5发布以来,它们在Perl中被称为“哈希”。您使用的任何资源似乎都已过时。请注意:
canonical
按字母顺序排序。因此,
10.2
将出现在
2
之前。