是否有更简单,更短的方法来执行此代码? [PHP,循环,数组] [关闭]

I have a code to modify the data that comes up from external API. However, I didn't like my code. I believe that there is a shorter way to do.

let me explain the flow:

I request to an api endpoint to get currency short codes. I mean $results contains these:

[0] => EURUSD
[1] => USDTRY
etc...

I want to save these as EUR, USD, TRY. I used str_split to do this. Also, I used array_unique to remove the same values. Right now, my array contains this.

[0] => EUR
[3] => USD
[5] => TRY

It's not enough for me. I need to change keys according to my database structure.

My table contains: id, name, created I have to rename each key as name. (btw I use Phnix to migrate and seeding)

$results = json_decode($httpResponse->getBody());

        $data = [];
        $prepared = [];

        foreach ($results as $key => $item) {
            $data = array_merge($data, str_split($item, 3));
        }

        $data = array_unique($data);

        foreach ($data as $key => $item) {
            array_push($prepared, ['name' => $item]);
        }

$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();

Do you have any clue for the best way?

in your code you make a lot of useless operation: considering that the lenght of the string is always 3 char you can simply use substr to obtain the currency code and use the currency code as key to make your array "unique" (if the same currency is added more than once, will "override" the previous one, whithout affecting the final result).

$results = json_decode($httpResponse->getBody());

$prepared = [];
foreach ($results as $item) {
  $itemName = substr($item,0,3);
  $prepared[$itemName] = ['name' => $itemName];
}

$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();