如何使用条件(PHP)替换数组值?

时间:2013-11-14 09:25:15

标签: php arrays

我只是想问一下,如果我使用二维数组,如何替换数组值?但对我来说困难的部分是我需要找到数组的现有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";

                }

            }

这是所有人,我希望你能帮助我。

3 个答案:

答案 0 :(得分:0)

尝试

$data[$i] = $data_add;

但我建议您使用数据库代替textfile

更改完整代码

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用array_search

找到该值