recherche

Maison  >  Questions et réponses  >  le corps du texte

php - 怎么用函数将一个关联数据里第一个下标的值和第二个下标的值对应起来?

$rs = [

"h" => ["id", "name", "region"],
"d" => [
    [100, "wang", "shanghai"],
    [101, "huang", "beijing"],
    [102, "zhang", "beijing"],
    [103, "li", "shanghai"],
]

];

$ret = rs2Array($rs);
print json_encode($ret);
/* 期望结果为:
[

{id: 100, name: "wang", region: "shanghai"},
{id: 101, name: "huang", region: "beijing"},
{id: 102, name: "zhang", region: "beijing"},
{id: 103, name: "li", region: "shanghai"}

]
*/

PHP中文网PHP中文网2786 Il y a quelques jours638

répondre à tous(2)je répondrai

  • 黄舟

    黄舟2017-04-11 09:53:54

    $rs = [
        "h" => ["id", "name", "region"],
        "d" => [
            [100, "wang", "shanghai"],
            [101, "huang", "beijing"],
            [102, "zhang", "beijing"],
            [103, "li", "shanghai"],
        ]
    ];
    
    foreach ($rs['d'] as $v) {
        $arr[] = array_combine($rs['h'], $v);
    }
    
    var_dump(json_encode($arr));
    

    répondre
    0
  • 怪我咯

    怪我咯2017-04-11 09:53:54

    $rs = [
        "h" => ["id", "name", "region"],
        "d" => [
            [100, "wang", "shanghai"],
            [101, "huang", "beijing"],
            [102, "zhang", "beijing"],
            [103, "li", "shanghai"],
        ]
    ];
    $ret = rs2Array($rs);
    print json_encode($ret);
    

    rs2Array函数如下:

    function rs2Array($arr = []) {
        $keyArr = $arr['h'];
        $valueArr = $arr['d'];
        return array_map(function($a) use($keyArr) {
            return array_combine($keyArr, $a);
        }, $valueArr);
    }

    répondre
    0
  • Annulerrépondre