首页 > 解决方案 > 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
        );
        }
    }  
}

标签: phparraysmatch

解决方案


使用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);

查看演示


推荐阅读