gpt4 book ai didi

javascript - 将数组从 php 转换为 javascript

转载 作者:行者123 更新时间:2023-12-03 06:42:55 25 4
gpt4 key购买 nike

我有来自数据库的数组,带有 json_encode,如下所示:

"[{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]"

但是当我像这样在 JavaScript 中显示时,如何使数组只显示记录而不显示字段/列名称:

JavaScript 数组:

{ 
"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"
}

应该用 php 还是 javascript 来完成?

谢谢

最佳答案

使用 JavaScript 处理:

function transfrom (arrs){
return arrs.reduce((init, arr) => {
init[arr.uid] = arr.name
return init
}
, {})
}

//usage

let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]
transfrom(arrs)

// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}

或者你可以用 PHP 处理它:

<?php
$arr = array (
array('uid' =>"595e7d", "name"=>"Elephant"),
array("uid" =>"701b03", "name" =>"Bird"),
array("uid" =>"29a8c", "name" =>"Lion")
);

function transform($v1, $v2) {
$v1[$v2["uid"]] = $v2["name"];
return $v1;
}

echo json_encode(array_reduce($arr, "transform", array()));
// {
// "595e7d": "Elephant",
// "701b03": "Bird",
// "29a8c": "Lion"
// }
?>

关于javascript - 将数组从 php 转换为 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37871756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com