dougou5852 2017-10-03 06:35
浏览 30

是否有更简单,更短的方法来执行此代码? [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?

  • 写回答

1条回答 默认 最新

  • dongyi6195 2017-10-03 06:49
    关注

    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();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多