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

If value found in multidimensional array, then make a change

我有一个多维数组存储在$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 中搜索类似 201 的值,如果匹配,则将该数组中的 $status 更改为 deleted?

例如:

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') {
       // change $status value of this specific array to 'delete'
       // WITHOUT changing the order of the arrays!
    }
}

您现有的循环就快完成了。为了能够修改 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';
    }
}

不使用引用,如果使用foreach:

$key => $value形式,也可以通过数组键修改
// 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';
    }
}