我正在尝试在 Perl 中重新创建一个 php 进程,但运气不佳(我不太了解 Perl)。
这是我的 php 代码:
$json = '{"0":{"name":"action","value":"none"},"1":{"name":"additionalTraining","value":"modulesRevisited"},"2":{"name":"additionalTrainingComments","value":""},"3":{"name":"additionalTraining","value":"moduleReporting"},"4":{"name":"additionalTrainingComments","value":""},"5":{"name":"additionalTrainingComments","value":""},"6":{"name":"anotherValue","value":""},"7":{"name":"1359436206","value":""},"8":{"name":"1359436207","value":""},"48":{"name":"actionId","value":""},"49":{"name":"multiSelect","value":"second"},"50":{"name":"multiSelect","value":"third"},"51":{"name":"radio","value":"1"},"52":{"name":"svgs","value":{"0":{"id":"drawing"},"1":{"id":"drawing"}}}}';
$decoded = json_decode($json,true);
$clean = array();
foreach($decoded as $Obj => $array){
if(array_key_exists($array['name'], $clean))
{
if(!is_array($clean[$array['name']]))
{
$value = $clean[$array['name']];
$clean[$array['name']] = array($value,$array['value']);
}
else
{
array_push($clean[$array['name']], $array['value']);
}
}
else
{
$clean[$array['name']]=$array['value'];
}
}
echo json_encode($clean);
更新: 这是我在 Perl 中尝试过的,我一直在碰壁:
use JSON;
use Data::Dumper;
use warnings;
use strict;
my @records = decode_json($json_text);
foreach my $element (@records)
{
print "$element\n";
}
我得到一个哈希引用。所以我尝试将第一行更改为:
my @records = @{ decode_json($json_text) }; #dereference function as it returns an arrayref, not a list
然后我在尝试循环时得到“不是数组引用”。
然后我尝试这样的事情并没有得到任何结果或错误:
my $records = decode_json($json_text);
my $i = 0;
my @records;
foreach my $entry (@{$records[0]}) {
my %listHash = %{$entry};
my $key;
my $value;
$i++;
while(($key, $value) = each(%listHash)) {
my $key;
my $value;
print "${key}_$i, $value\n";
}
}
然后我尝试将它们中的所有部分组合起来以获得我想要的输出,而我最接近的是:
my %records = %{ decode_json($json_text) };
while ( my ($key, $value) = each %records )
{
my $records;
#print "key: $key, value: $records{$key}\n";
while ( my ($key, $value) = each %{$value} )
{
print "key: $key, value: $value\n";
}
}
但这给了我这样的输出:
key: name, value: anotherValue
key: value, value: third
key: name, value: multiSelect
key: value, value: moduleReporting
而我需要像这样的输出
key: anotherValue, value: third
key: multiSelect, value: moduleReporting
我哪里错了?
如何在 Perl 中重新创建相同的结果?非常感谢您的帮助。