dongxinyue2817 2017-04-23 10:26
浏览 55

PHP:使用已编辑的行更新JS文件

I have the following AngularJS file called

productFactory.js

with a list of products and their details and I want to update 1 of the products.

"use strict"; 

var productFactory = angular.module('productFactory', []);

productFactory.factory('productFactory', function () {

var productFactory = {};

productFactory.products = [
    {
        productId: 1,
        name: "Product1",
        category: "Urban",
        desc: "Lorem Ipsum",
        image: "placeholder1.png;placeholder2.png;placeholder3.png",
        price: 30,
        qty: 6,
        variation: ""
    },
    {
        productId: 2,
        name: "Product2",
        category: "Street Wear",
        desc: "Lorem Ipsum",
        image: "placeholder1.png;placeholder2.png;placeholder3.png",
        price: 40,
        qty: 10,
        variation: "6,7,8,9,10,11,12"
    }
];

return productFactory;
});

In PHP I can run this script to write to the file

<?php
$script="SOME_CONTENT";
$fileName="productFactory.js";
file_put_contents($fileName, $script);
?>

How do I update just one of the products by it's 'productId'?

  • 写回答

1条回答 默认 最新

  • douchongbc72264 2017-04-23 10:34
    关注

    Best way would be to store products in some database (it could be simple JSON file which you have in productFactory.products variable.

    If they were stored in JSON, you would load the file in PHP, parse it to an object with json_decode($str);, then edit what you want in that object and after that just convert it back to JSON string with (json_encode($obj);).

    If you store them in a database like MySQL, the PHP processing would be simpler I think (simply call an UPDATE query for given product id).

    PHP example for processing edit request:

    $path = "/path/to/products.json";
    $data = file_get_contents($path);
    $json = json_decode($string);
    
    foreach ($json as & $product) {
        // process only correct product
        if ($product->productId !== $_POST['productId']) {
            continue;
        }
    
        foreach ($_POST as $key => & $value) {
            // here should be some data validation probably
            if (isset($product[$key]) {
                $product[$key] = $value;
            }
        }
    }
    
    $newData = json_encode($json);
    file_put_contents($path, $newData);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值