我正在尝试创建一个CRUD应用程序,但遇到了麻烦,如果有人能给我指出正确的方向,我将不胜感激,谢谢。
您好,我在使用来自json的数据时遇到了困难。
我已经在这里使用过了,并且工作正常。
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}这是我的控制器
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}这是我的路线
Route::get('/product' , [ProductController::class, 'index'] );我如何在我的控制器上使用它,我应该设置什么路径来创建一个产品
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}这就是我尝试输入代码的地方。
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}发布于 2020-11-16 23:19:19
您的函数addNewProduct()在调用时需要7个参数。
你得到这个错误是因为你不能提供你的函数正在寻找的参数。
在上面的代码中,您传递的是字符串格式的'products.json'。
让我们假设它是一个JSON数据。它仍然会失败,因为您只向一个需要7个参数的函数传递了1个参数。
你可以做的就是把它改成
public static function addNewProduct($data)
{
// code here
}然后,您可以传递JSON数据,然后使用循环遍历每个json。
https://stackoverflow.com/questions/64859883
复制相似问题