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?