php - PHP:根据键的值修改关联数组
问题描述
我有一个这样的数组
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 3
[type] => default
[place] => 2
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
这个数组是从这个 php 创建的
for($count=1;$count <= 3;$count++){
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
现在,如果 php mysql 数据找到该位置,我想更改此数组的结果。例如我有这个数组。
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
如您所见,第二个数组位于“位置 2”。现在我希望结果是这样的
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
如何做到这一点?我已经完成了 array_search 函数,但没有运气。任何人请帮助我
=======================编辑完整代码======================== ======== 这是代码,我正在显示数据库中的数据并在while循环函数中调用它
for($count=1;$count <= $max_places;$count++){
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[$key] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
}
==========================交换代码======================= =======
while($arr = $stmts->fetch()){
$array[] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
for($count=1;$count <= $max_places;$count++){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
}
解决方案
使用array_column()
witharray_search()
获取需要修改的数组键。请参阅以下代码片段:
<?php
// Here is trick; get the key of the array using array_column
$key = array_search('2', array_column($array, 'place'));
// If any key found modify the array
if ($key && array_key_exists($key, $array)) {
$array[$key] = [
'id' => 7,
'type' => 1,
'place' => 2,
'description' => 'This is item place 2',
'image' => 'this_is_the_image.png',
];
}
print_r($array);
查看演示
推荐阅读
- json - 如何使用播放框架在 Json 中转换响应体
- c++ - 为什么从向量构建一个集合是 O(N)
- ffmpeg - 来自原始视频流的 FFMPEG 持续时间不正确
- database - MongoDB跨ID数组加入
- html - 如何在按钮单击时在 jquery 中创建多个引导卡
- javascript - 如何从多个输入类型 =“文件”中删除某些文件?
- docker - 将 prometheus 数据挂载到主机卷 /mnt/resources/
- python - 在 python 中创建简单的 tar.gz 时会创建嵌套的 tar
- javascript - 使用提示中的值作为 highcharts 导出文件名
- r - 添加列时分解