使用合格的 id 列值更新行中的列值

问题描述 投票:0回答:2

如何在 livewire 或 laravel 中更新 push_array 数据中的数据,请参阅下面的数组数据。

[
    ["id" => 0, "input_Data" => "Up to 15 Groups / Month"],
    ["id" => 1, "input_Data" => "Up to 60 CSV File Importing / Month"],
    ["id" => 2, "input_Data" => "Up to 15 SMTP Config"],
    ["id" => 3, "input_Data" => "Up to 20 Email Template Can Make"],
    ["id" => 4, "input_Data" => "Up to 150 Ai Writer Call / Month"],
    ["id" => 5, "input_Data" => "Markitach SMTP Limit 1000 Emails"]
]

我想更新

input_Data
,其中 id 为
3
。我该怎么办?

php arrays laravel replace laravel-livewire
2个回答
0
投票
$data = [
    0 => [
        "id"         => 0,
        "input_Data" => "Up to 15 Groups / Month"
    ],
    1 => [
        "id"         => 1,
        "input_Data" => "Up to 60 CSV File Importing / Month"
    ],
    2 => [
        "id"         => 2,
        "input_Data" => "Up to 15 SMTP Config"
    ],
    3 => [
        "id"         => 3,
        "input_Data" => "Up to 20 Email Template Can Make"
    ],
    4 => [
        "id"         => 4,
        "input_Data" => "Up to 150 Ai Writer Call / Month"
    ],
    5 => [
        "id"         => 5,
        "input_Data" => "Markitach SMTP Limit 1000 Emails"
    ]
];
foreach ($data as $key => $aData) {
    if ($aData['id'] == 3) {
        $data[$key]['input_Data'] = 'data changed';
    }
}

0
投票

在分配数组之前更改此数据集可能会更好。如果您正在处理数据库(这相当符合逻辑),那么请更新数据库,以便您的代码不需要执行此工作。

否则,一旦找到匹配项,就通过“中断”循环来将时间复杂度降至最低。 演示

$array = [
    ["id" => 0, "input_Data" => "Up to 15 Groups / Month"],
    ["id" => 1, "input_Data" => "Up to 60 CSV File Importing / Month"],
    ["id" => 2, "input_Data" => "Up to 15 SMTP Config"],
    ["id" => 3, "input_Data" => "Up to 20 Email Template Can Make"],
    ["id" => 4, "input_Data" => "Up to 150 Ai Writer Call / Month"],
    ["id" => 5, "input_Data" => "Markitach SMTP Limit 1000 Emails"]
];

$find = 3;
$replace = "Up to the boss";
foreach ($array as &$row) {
    if ($row['id'] === $find) {
        $row['input_Data'] = $replace;
        break;
    }
}
var_export($array);

从 PHP8.4 开始,您可以使用

array_find_key()
,它的设计目的是在找到合格的匹配项后立即有条件地停止迭代。 演示

$find = 3;
$replace = "Up to the boss";
$index = array_find_key($array, fn($row) => $row['id'] === $find);
if ($index !== null) {
    $array[$index]['input_Data'] = $replace;
}
var_export($array);
© www.soinside.com 2019 - 2024. All rights reserved.