0

我只想问如果我使用二维数组,如何替换数组值?但对我来说困难的部分是我需要找到数组的现有 ID 值。该阵列是我需要用我的新阵列替换的阵列。

这是我的代码假设我们有这个输出。

Array
(
    [0] => Array
        (
            [restaurant_id] => 1519
            [new_lat] => 14.63807
            [new_long] => 121.03158
            [date_updated] => 2013-11-14 16:40:34
        )

    [1] => Array
        (
            [restaurant_id] => 5413
            [new_lat] => 14.63877
            [new_long] => 121.03265
            [date_updated] => 2013-11-14 17:11:53
        )

)

在我的 PHP 代码中,我有这个:

            //THIS IS MY NEW ARRAY
            $data_add = array( 
                'restaurant_id' => $restaurant_id, 
                'new_lat' => $new_lat_entry, 
                'new_long' => $new_long_entry, 
                'date_updated' => date('Y-m-d H:i:s') 
            ); 


            //THIS WILL GET THE FILE FROM THE TXT AND MAKE IT AN ARRAY
            $data = unserialize(file_get_contents('addresses.txt'));

            //$data[] = $data_add; 

            $temp_array = array();

                    //USE THIS FOR COMPARING. THIS IS THE ID FROM MY NEW ARRAY.   
            $target = $data_add['restaurant_id'];

                    //LOOP TO SEARCH
            for ($i = 0; $i < count($data); $i++) {

                            //GET ID FROM EXISTING TXT FILE
                $get_id = $data[$i]['restaurant_id'];

                            //THEN FIND
                if($get_id == $target){

                    //if found update/delete specific row

                    //THERE'S THE PART THAT I NEED TO UPDATE

                    break;

                }else{

                    //if not found add
                    echo "not found";

                }

            }

就这些了,希望大家能帮帮我,谢谢。

4

3 回答 3

0

您可以使用函数http://us2.php.net/array_key_exists来检查密钥是否存在。

于 2013-11-14T09:30:47.020 回答
0

尝试

$data[$i] = $data_add;

但我建议你使用数据库而不是文本文件

更改完整代码

//THIS IS MY NEW ARRAY
        $data_add = array( 
            'restaurant_id' => $restaurant_id, 
            'new_lat' => $new_lat_entry, 
            'new_long' => $new_long_entry, 
            'date_updated' => date('Y-m-d H:i:s') 
        ); 


        //THIS WILL GET THE FILE FROM THE TXT AND MAKE IT AN ARRAY
        $data = unserialize(file_get_contents('addresses.txt'));

        $target = $data_add['restaurant_id'];

        //LOOP TO SEARCH
        $is_new = true;
        for ($i = 0; $i < count($data); $i++) {

            //GET ID FROM EXISTING TXT FILE
            $get_id = $data[$i]['restaurant_id'];

            //THEN FIND
            if($get_id == $target){
                $data[$i] = $data_add;
                $is_new = false;
                break;
            }
        }
        //IF NOT FOUND DURING CYCLE
        if ($is_new) {
               //Add new value
               $data[] = $data_add;
        }
于 2013-11-14T09:28:15.383 回答
0

您可以使用array_search找到值

于 2013-11-14T11:43:23.460 回答