如果在多维数组中找到值,则进行更改

时间:2015-01-11 22:16:49

标签: php arrays multidimensional-array

我有一个存储在$t_comments中的多维数组:

Array (
    [0] => Array
        (
            [0] => 889
            [1] => First comment
            [2] => 8128912812
            [3] => approved
        )

    [1] => Array
        (
            [0] => 201
            [1] => This is the second comment
            [2] => 333333
            [3] => approved
        )

    // There is more...
)

我像这样遍历数组:

foreach($t_comments as $t_comment) {
    $id = $t_comment[0]; // id
    $comment = $t_comment[1]; // comment
    $timestamp = $t_comment[2]; // timestamp
    $status = $t_comment[3]; // status
}

我的问题:如何在$id中搜索数组搜索{​​{1}}之类的值,如果匹配,则将该数组中的201更改为$status }?

例如:

deleted

1 个答案:

答案 0 :(得分:1)

你现有的循环几乎就在那里。为了能够修改foreach循环内的值并使其实际反映在原始数组中,您需要使用引用&。这是第一个例子in the foreach docs

所做的更改不会对原始外部数组或修改后的子数组的顺序产生任何影响。 Demonstration...

只需使用新值覆盖循环内的$t_comment[3]

// You must use a reference &t_comment to modify this
foreach($t_comments as &$t_comment) {
    $id = $t_comment[0]; // id
    $comment = $t_comment[1]; // comment
    $timestamp = $t_comment[2]; // timestamp
    $status = $t_comment[3]; // status

    if ($id == '201') {
        // Set a new value for the [3] key
        // Don't modify the variable $status unless it was also
        // declared as a reference. Better to just modify the array
        // element in place.
        $t_comment[3] = 'deleted';
    }
}

如果您使用$key => $value foreach形式的// Use the $key => $value form foreach($t_comments as $key => $t_comment) { $id = $t_comment[0]; // id if ($id == '201') { // Set a new value for the [3] key // Referencing the *original array variable* by key // rather than the iterator $t_comment $t_comments[$key][3] = 'deleted'; } } ,则无需使用引用,也可以使用数组键对其进行修改:

{{1}}