如何使用PHP将数组映射为键值?

时间:2018-05-02 13:59:19

标签: php

我需要使用PHP将json数组值排序为ker相同的键值。我的代码如下。

echo json_encode( $output );

// Output:
[
    {
        "first_name":"robin",
        "last_name":"sahoo",
        "reg_no":12,
        "paper_code":"BA001"
    },
    {
        "first_name":"robin",
        "last_name":"sahoo",
        "reg_no":12,
        "paper_code":"BA002"
    },
    {
        "first_name":"Rama",
        "last_name":"Nayidu",
        "reg_no":13,
        "paper_code":"BA001"
    }
];

以上是我的数组列表。在这里,我需要按reg_no对所有行值进行排序,这意味着如果有多个行包含相同的reg_no,那么加入这两个名称的行将很少,我的预期输出应如下所示。

预期产出:

[
    {
        'name':"robin sahoo",
        "reg_no":12,
        "paper1":"BA001",
        "paper2":"BA002",
        "paper3":"",
        "paper4":""
    },
    {
        'name':"Rama Nayidu",
        "reg_no":13,
        "paper1":"BA001",
        "paper2":"",
        "paper3":"",
        "paper4":""
    }
]

此处paper1,paper2,paper3,paper4将被串行选择意味着假设同一reg_no=12有第一行paper_code= BA001然后它将是paper1=BA001而第二行paper_code=BA002则会是paper2=BA002等等。这里我使用PHP来映射这个数组。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,这可能是一个解决方案:

<?php

//defining source
$array[0]['first_name']='robin';
$array[0]['last_name']='sahoo';
$array[0]['reg_no']=12;
$array[0]['paper_code']='BA001';

$array[1]['first_name']='robin';
$array[1]['last_name']='sahoo';
$array[1]['reg_no']=12;
$array[1]['paper_code']='BA002';

$array[2]['first_name']='Rama';
$array[2]['last_name']='Nayidu';
$array[2]['reg_no']=13;
$array[2]['paper_code']='BA001';

//var_dump($array)
echo json_encode($array);

//avoid warnings
$reg_no = array();

//loop through source array
foreach ($array as $key => $value) {
  //saving used reg_no
  $this_reg_no = $value['reg_no'];
  if(!isset($reg_no[$this_reg_no])){
    //it's the first time I meet $this_reg_no
    //add it to the known reg_no and save his key
    $reg_no[$this_reg_no]=$key;
    $result[$key]['name'] = $value['first_name'].' '.$value['last_name'];
    $result[$key]['reg_no'] = $value['reg_no'];
    $result[$key]['paper1'] = $value['paper_code'];
    //in $papers_count I count the number of paper_code saved.
    //the key is the same index as in $result while the value is the counter for that reg_no
    $papers_count[$key] = 1;
  }
  else{
    //I met $this_reg_no already, update existing key
    $papers_count[$reg_no[$this_reg_no]]++;
    $result[$reg_no[$this_reg_no]]['paper'.$papers_count[$reg_no[$this_reg_no]]] = $value['paper_code'];
  }
}

//var_dump($result)
echo json_encode($result);


 ?>

结果:

[{"first_name":"robin","last_name":"sahoo","reg_no":12,"paper_code":"BA001"},{"first_name":"robin","last_name":"sahoo","reg_no":12,"paper_code":"BA002"},{"first_name":"Rama","last_name":"Nayidu","reg_no":13,"paper_code":"BA001"}]{"0":{"name":"robin sahoo","reg_no":12,"paper1":"BA001","paper2":"BA002"},"2":{"name":"Rama Nayidu","reg_no":13,"paper1":"BA001"}}