如何在Livewire或laravel中更新push_array数据中的数据

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

如何更新 livewire 或 laravel 中的 push_array 数据中的数据,请参阅下面的数组数据。我尝试了但没有成功只是我想更新我用 array_push() 推入数组的数据

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

我想更新 input_Data 其中 id 3,我该怎么做。请帮助我。

我尝试了但没有成功:(

laravel 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.