php - 怎么用函数将一个关联数据里第一个下标的值和第二个下标的值对应起来?
PHP中文网
PHP中文网 2017-04-11 09:51:54
0
2
631

$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中文网

认证高级PHP讲师

membalas semua(2)
黄舟
$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));
刘奇
$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);
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan