【问题标题】:PHP: Modify an associative array based on value of a keyPHP:根据键的值修改关联数组
【发布时间】:2020-03-01 08:57:15
【问题描述】:

我有一个这样的数组

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
        );
        }
    }  
}

【问题讨论】:

    标签: php arrays match


    【解决方案1】:

    您可以使用内置的 array_multisort() 功能。

    从 php.net 复制的示例 一种对多维数组中的键进行排序的好方法,而无需先知道数组中有哪些键:

    <?php
        $people = array(
            array("name"=>"Bob","age"=>8,"colour"=>"red"),
            array("name"=>"Greg","age"=>12,"colour"=>"blue"),
            array("name"=>"Andy","age"=>5,"colour"=>"purple")
        );
    
    var_dump($people);
    
    $sortArray = array();
    
    foreach($people as $person){
        foreach($person as $key=>$value){
            if(!isset($sortArray[$key])){
                $sortArray[$key] = array();
            }
            $sortArray[$key][] = $value;
        }
    }
    
    $orderby = "name"; //change this to whatever key you want from the array
    
    array_multisort($sortArray[$orderby],SORT_DESC,$people);
    
    var_dump($people);
    ?>
    

    没有检查您的数组键是否存在,或者您正在搜索的数组数据是否确实存在,但很容易添加。

    查看https://www.php.net/manual/de/function.ksort.php(用户贡献)和 https://www.php.net/manual/de/function.array-multisort.php

    【讨论】:

    • 这如何回答 OP 问题?
    【解决方案2】:

    使用array_column()array_search() 获取需要修改的数组key。见以下代码sn -p:

    <?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);
    

    demo

    【讨论】:

    • 请检查我的第一篇文章,编辑将完整的代码。我正在从数据库中获取数据并在 while 循环中调用它
    【解决方案3】:

    试试:

    for($count=1;$count <= 3;$count++){
        if(array_search($count,array_column("place",$array_from_db)) continue;
        $places_array = array(
            "id" => "3",
            "type" => "default",
            "place" => $count,
            );
    }
    

    这将跳过:

    Array
    (
        [id] => 3
        [type] => default
        [place] => 2
    )
    

    ===========编辑=============

    while($arr = $stmts->fetch())
    {
        $array[$arr['place']] = [
            "id" => $arr['id'],
            "type" => $arr['type'],
            "place" => $arr['place'],
            "url" => $arr['url'],
            "image" => $arr['image']
        ];
    }
    for($count=1;$count <= $max_places;$count++){
        if(!isset($array[$count])){
            $array[$count] = array(
                "id" => $res['id'],
                "type" => "default",
                "place" => $count
            );
        }
    }  
    ksort($array);
    

    【讨论】:

    • 继续是什么意思?得到这个解析错误:语法错误,意外的“继续”(T_CONTINUE)在
    • continue 用于循环结构中以跳过当前循环迭代的其余部分并在条件评估处继续执行,然后在下一次迭代的开始处继续执行。 ,参考:php.net/manual/en/control-structures.continue.php
    • 尝试使用这个if(array_search($count,array_column("place",$array_from_db)) $count++;而不是if(array_search($count,array_column("place",$array_from_db)) continue;
    • 请检查我的第一篇文章,编辑将完整的代码。我正在从数据库中获取数据并在 while 循环中调用它
    • 尝试交换whilefor
    【解决方案4】:

    找到答案了,谢谢大家的帮助。

    这就是诀窍

    首先我们需要像这样确定主数组

    for($count=1;$count <= $max_places;$count++){
            $array[$count] = array(
                "id" => $res['id'],
                "type" => "default",
                "place" => $count
            );
    } 
    

    然后我们需要找到哪个地方不可用并显示匹配项。

    while($arr = $stmts->fetch()){
        $key = array_search($arr['place'], array_column($array, 'place'));
        $key+=1;
        if($key && array_key_exists($key, $array)) {
            $array[$arr['place']] = [
                "id" => $arr['id'],
                "type" => $res['type'],
                "place" => $arr['place'],
                "url" => $arr['url'],
                "image" => $arr['image']
            ];
        }
    }
    

    诀窍在于

    $key+=1;
    

    因为数组中的默认键是0。 希望这可以帮助其他人

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2013-09-13
      • 1970-01-01
      • 2017-06-17
      • 2021-03-25
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多