在 PHP 中编辑具有新值的数组


Edit an array with new values in PHP

我有这个数组:

Array
(
    [datas] => Array
        (
            [General] => Array
                (
                    [0] => Array
                        (
                            [id] => logo
                            [size] => 10
                        )
                )
            [Rooms] => Array
                (
                    [0] => Array
                        (
                            [id] => room_1
                            [size] => 8
                        )
                    [1] => Array
                        (
                            [id] => room_2
                            [size] => 8
                        )
                    [2] => Array
                        (
                            [id] => room_3
                            [size] => 8
                        )
                )
        )
)

当我收到这样的信息时,我需要更新它:

$key = 'room_3';
$toChange = '9';

所以在我的数组中,我想改变room_3size

我将始终编辑相同的元素(即 size )。

<小时 />

我尝试过:

// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
    foreach ($datas as $d) {
        if (array_search($got, $d)) {
            if (in_array($to_find, array_keys($d))) {
                return trim($d[$to_find]);
            }
        }
    }
}

但它不起作用...

你能帮帮我吗?

谢谢。

function getDatas($datas, $got, $to_find) {
    foreach($datas['datas'] as $key => $rows) {
        foreach($rows as $number => $row) {
            if($row['id'] == $got) {
                // u can return new value
                return $row['size'];
                // or you can change it and return update array
                $datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
                return $datas;
            }
        }
    }
}
function changeRoomSize (&$datas, $roomID, $newSize ){
        //assuming that you have provided valid data in $datas array
        foreach($datas['datas']['Rooms'] as &$room){
            if($room['id'] == $roomID){
                $room['size'] = $newSize;
                break;//you can add break to stop looping after the room size is changed
            }
        }
    }
    //--- > define here your array with data
    //and then call this function
    changeRoomSize($data,"room_3",9);
    //print the results
    var_dump($data);

这是一个三维数组,如果你想改变这个值,就这样做:

$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
    foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
        if ($v2['id'] == $key)) {
           $rooms[$k1][$k2]['size'] = $toChange;
        }
    }
    return $rooms;
}
print_r($array);