0

对不起我的标题。我只是不知道怎么问这个。长话短说,我只需要替换数组的某个部分。假设我们有这个数组:

Array
(
      [0] => Array
        (
            [restaurant_id] => 1236
            [new_lat] => 76
            [new_long] => 86
            [date_updated] => 2013-11-15 17:20:58
        )

      [1] => Array
        (
            [restaurant_id] => 1247
            [new_lat] => 6
            [new_long] => 5
            [date_updated] => 2013-11-15 17:20:58
        )

      [2] => Array
        (
            [restaurant_id] => 7456
            [new_lat] => 21
            [new_long] => 12
            [date_updated] => 2013-11-15 17:20:58
        )

)

现在我需要用这个替换索引 2:

Array(
     [2] => Array
        (
            [restaurant_id] => 1236
            [new_lat] => 2
            [new_long] => 1
            [date_updated] => 2013-11-15 17:20:58
        )
)

如果我发现有一个现有的 restaurant_id,我需要更换。如果有。更新该行。我没有添加新数组。

我有一个想法,但我不知道该怎么做。我的想法是:

  1. 反序列化数组(因为我的数组是序列化形式)

  2. 找到目标索引。如果找到删除该索引并将我的新索引添加到数组的底部,然后再次序列化它。如果未找到,则仅在数组底部添加并序列化。

我只是不知道我是否删除了索引。如果索引会自动移动。意味着如果我删除索引 2,索引 3 将成为索引 2,而我的新数组是索引 3。

好的,这就是所有的家伙。谢谢。

4

5 回答 5

2

获取包含目标元素的引用变量并对其进行修改。

foreach ($myArray as $myKey => &$myElement) 
{
 if ($myElement['restaurant_id'] == WHAT_IM_LOOKING_FOR)
 {
  $myElement['new_lat'] = ...;
  ...;
 }
}
于 2013-11-15T09:57:04.300 回答
1

您不必删除该索引;只需覆盖它。

  1. 反序列化

  2. 找到目标索引。如果找到,只需覆盖(而不是删除)。如果没有找到,只需在末尾添加[].

覆盖:

$my_array[2] = array(
    'restaurant_id' => 1236,
    'new_lat' => 2,
    'new_long' => 1,
    'date_updated' => '2013-11-15 17:20:58'
);

此代码将用此新代码覆盖您的索引2。你不需要之前取消它。

于 2013-11-15T09:50:00.777 回答
1

ifrestaurant_id是一个唯一的 ID,如果你重新组织它,处理该数组会更容易:

Array
(
      [1236] => Array
        (
            [new_lat] => 76
            [new_long] => 86
            [date_updated] => 2013-11-15 17:20:58
        )

      [1247] => Array
        (
            [new_lat] => 6
            [new_long] => 5
            [date_updated] => 2013-11-15 17:20:58
        )

      [7456] => Array
        (
            [new_lat] => 21
            [new_long] => 12
            [date_updated] => 2013-11-15 17:20:58
        )

)

之后,您可能会发现通过以下方式访问更容易

 ... isset($arr[$restaurantId]) ....

$arr[$restaurantId] = array('new_lat' => 42, .... )

将插入/更新不知道该条目是否存在的任何知识。

于 2013-11-15T09:59:10.107 回答
0

好的,用 id 取消设置元素,然后使用,然后添加一个新元素:

    unset($array[2]); // unset number 2
    $array = array_values($array); // resort
    $array[] = $newStuff; // add

祝你好运

于 2013-11-15T09:49:47.800 回答
0

如果使用 unset 函数,索引将保持为空。

例如,如果您的 $array 有 4 个值,0 1 2 3,如果您取消设置索引 2,则索引 3 将保持为 3,并且新添加的数组将是索引 4。

以下代码将说明这一点:

$a = array("zero", "one", "two", "three");
var_dump($a);
unset($a[2]);
var_dump($a);
$a[]="four";
var_dump($a);
于 2013-11-15T09:50:35.560 回答