简体   繁体   中英

PHP: Modify an associative array based on value of a key

I have an array like this

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

This array is created from this php

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

Now I want to change the result of this array if the place is found by the php mysql data. For example I have this array.

Array
(
    [id] => 7
    [type] => 1
    [place] => 2
    [description] => This is item place 2
    [image] => this_is_the_image.png
)

As you can see that the second array is in "place 2". Now I want the result be like this

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
)

How to achieve this? I have already done with array_search function but no luck. anyone please help me

=======================EDIT FULL CODE================================ Here is the code, I'm showing the data from database and call it in while loop function

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']
            ];
        }
    }
}

=========================SWAPPED CODE==============================

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

You can use the built in array_multisort() function.

Example copied from php.net A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

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

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.

Check out https://www.php.net/manual/de/function.ksort.php (user contributes) and https://www.php.net/manual/de/function.array-multisort.php

Try :

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

This will skip:

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

=========== EDIT =============

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

Use array_column() with array_search() to get the array key that needs to be modified. See the following code snippet:

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

See the demo

Found the answer, thanks for all help.

Here is the trick

first we need to determine the main array like this

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

Then we need to find which place is not available and show the matches.

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']
        ];
    }
}

The trick is in the

$key+=1;

Because the default key in array is 0. Hope this can help others

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM