Skip to content
Advertisement

Problem with update database from API in Laravel PHP

I have a database of items, now I need to update the pictures in 10,000 records in the database, I make an API request, I receive an answer, but I just cannot process the answer correctly.

I received result:

{"result":{"items":{"★ StatTrak™ Bowie Knife | Safari Mesh (Battle-Scarred)":{"actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D751048845621896210","name":"Inspect in Game..."}],"background_color":null,"commodity":false,"descriptions":[{"app_data":"","type":"html","value":"Exterior: Battle-Scarred"},{"app_data":"","color":"#99CCFF","type":"html","value":"This item features StatTrak™ technology, which tracks certain statistics when equipped by its owner."},{"app_data":"","color":"#CF6A32","type":"html","value":"This item tracks Confirmed Kills."},{"app_data":"","type":"html","value":"This full-tang sawback Bowie knife is designed for heavy use in brutal survival situations. It has been spray-painted using mesh fencing and cardboard cutouts as stencils.nn<i>A predator is a predator, no matter the environment</i>"}],"icon_url":"-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJfwObaZzRU7dCJlo-cnvLLIKvum25C4Ppli-f-_Yn0nk36-EZrYjz2cNedIVRqMFCE_VO3xOfqgpfutJWfySRi7nRw7Snan0DmhQYMMLIiC3JRKA"

And i need compare the name, and write in database icon_url value.

But always i received error:

Undefined array key "items" in:

    foreach ($prices['items'] as $key => $price) {
        $newPrices[$key] = $price['icon_url'];
    }

My code:

public function update_information()
{
    $prices = json_decode(file_get_contents('https://api.hexa.one/market/items/730?key=O2XDN99XN45XY5EN83CEP3ZZ8X5WDRY4'), true);

    if (!$prices['result']) {
        dd('Error');
    }

    $newPrices = [];

    foreach ($prices['items'] as $key => $price) {
        $newPrices[$key] = $price['icon_url'];
    }

    $totalUpdated = 0;

     foreach (AllItem::query()->get() as $itemDB) {
        $fullName = $itemDB->market_hash_name;
        if( $itemDB->exterior ) {
            $fullName = $itemDB->market_hash_name . '(' . $itemDB->exterior . ')';
        }


        if (!isset($newPrices[$fullName])) {
            continue;
        }


        $itemDB->update(['image' => $newPrices[$fullName]]);
        $totalUpdated++;
        $itemDB->save();

        $totalUpdated++;
    }

    dd('done. Updated: ' . $totalUpdated);
}

How i can fix it? Hope for your help!

Advertisement

Answer

You forgot the result. The items key is in the result.

array:1 [
  "result" => array:2 [
    "items" => array:17990 [
        ....
    ]
    "updated" => 1618501391
  ]
]

So, you have to replace it with:

foreach ($prices['result']['items'] as $key => $price) {
    ...
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement