【问题标题】:Format and split csv/json on php在 php 上格式化和拆分 csv/json
【发布时间】:2018-05-24 11:57:56
【问题描述】:

我正在尝试使用此 API 来填充我的 mysql 数据库,如果出现“new itens”,我需要更新,并更新所有价格。我已经有了这个脚本的后端结构,但我需要将名称与每件商品的价格分开。

API(可以在浏览器上打开):https://api.csgofast.com/price/all

我怎样才能做到这一点,比如最好的方法?

我试图在“:”上爆炸,但有这样的情况:

"Prismatic: Miasmatic Grey": 39.48,

所以爆炸不起作用。

感谢您的建议。

代码:

protected function populateItems()
{
    $items = json_decode(file_get_contents(API_URL));
    foreach($items as $item) {
        Item::create([
            'name' => $i[0],
            'price' => $i[1]
        ]);
    }
    die('end');
}

我也试过了,但在“:”上失败了

protected function populateItems()
{
    $body = file_get_contents(API_URL);
    $items_parsed = str_replace('{', '', $body);
    $items_converted = str_replace('}', '', $items_parsed);
    $items = str_getcsv($items_converted);
    foreach($items as $item) {
        // Item::create([
            // 'name' => $i[0],
            // 'price' => $i[1]
        // ]);
    }
    echo 'Fim da execução.';
    die;
}

回答回复:

object(stdClass)#470 (15689) { ["Sticker | Counter Logic Gaming (Foil) | MLG 
Columbus 2016"]=> float(2.14) ["Sticker | RUBINO (Foil) | Cologne 2016"]=> 
float(1.26) ["P2000 | Granite Marbleized (Well-Worn)"]=> float(0.01) ["★ Bayonet 
| Fade (Minimal Wear)"]=> float(226.55)

【问题讨论】:

  • 请在问题本身中包含 API 响应的示例以及您尝试过的代码、预期结果和当前产生的结果。请阅读:How to create a Minimal, Complete, and Verifiable exampleHow do I ask a good question?
  • 你为什么不能直接 json_decode 所有数据?
  • 如果我使用 json_decode,我得到了这个答案 object(stdClass)#470 (15689) { ["Sticker | Counter Logic Gaming (Foil) | MLG Columbus 2016"]=> float(2.14) ["贴纸 | RUBINO (Foil) | Cologne 2016"]=> float(1.26) ["P2000 | Granite Marbleized (Well-Worn)"]=> float(0.01) ["★ 刺刀 | Fade (略有磨损)"]=> float(226.55) 是不是很容易操作?

标签: php json split format


【解决方案1】:

我刚刚遇到了问题。我不习惯使用 $key => $value 的 for each,所以我这样解决了:

$items = json_decode(file_get_contents(API_URL));
    foreach($items as $item => $price) {
        Item::create([
            'name' => $item,
            'price' => $price
        ]);
    }

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2014-02-05
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多