欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php多维数组把value值赋值到key,该怎么处理

程序员文章站 2022-05-10 10:53:36
...
php多维数组把value值赋值到key
php多维数组把value值赋值到key,改成这种效果,怎么做
"image": [
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 1
},
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 2
},
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 3
}
]
改成:
"image": [
{
"1": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 1
},
{
"2": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 2
},
{
"3": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 3
}
]
------解决思路----------------------




$arr=array(
array(
'local_path' =>'aaaaa',
'picture_id' =>1
),
array(
'local_path'=>'bbbbbbb',
'picture_id'=>2
),
array(
'local_path'=>'ccccccc',
'picture_id'=>3
),
);

function change($arrr,$a=0){
foreach($arrr as $key=>$value){
$arr[$a][$value['picture_id']]=$value['local_path'];
$arr[$a]['picture_id']=$value['picture_id'];
$a++;

}
return $arr;
}


$arry=change($arr);

print_r($arry);


?>


------解决思路----------------------
你这不是 php 的数组,是 json
$s = "image": [
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 1
},
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 2
},
{
"local_path": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 3
}
]
TXT;
$a = json_decode('{'. $s .'}', 1);

foreach($a['image'] as &$item) {
$item = array(
$item['picture_id'] => $item['local_path'],
'picture_id' => $item['picture_id']
);
}
print_r($a);
Array
(
[image] => Array
(
[0] => Array
(
[1] => /upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg
[picture_id] => 1
)

[1] => Array
(
[2] => /upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg
[picture_id] => 2
)

[2] => Array
(
[3] => /upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg
[picture_id] => 3
)

)

)
还原回 json
echo json_encode($a, JSON_PRETTY_PRINT 
------解决思路----------------------
JSON_UNESCAPED_SLASHES);
{
"image": [
{
"1": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 1
},
{
"2": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 2
},
{
"3": "/upload/14d4aaf3c5ef5b93e6c4c7418428ea71.jpg",
"picture_id": 3
}
]
}
php多维数组把value值赋值到key,该怎么处理

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频