Label.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: xiaofeng
  5. * Date: 2018/10/7
  6. * Time: 5:55 PM
  7. */
  8. namespace common\api;
  9. use common\models\Characteristic;
  10. use Yii;
  11. class Label{
  12. //特色主题
  13. public function Characteristic($id,$num = 3)
  14. {
  15. $cache = Yii::$app->cache;
  16. // $cache->delete(Yii::$app->params['cacheKey']['characteristic']);
  17. $cacheData = $cache->get(Yii::$app->params['cacheKey']['characteristic']);
  18. if(!$cacheData)
  19. {
  20. $char = \common\models\Characteristic::find();
  21. $char->andWhere(['del'=>1]);
  22. $char->andWhere(['is_show'=>1]);
  23. $data = $char->asArray()->all();
  24. if(!empty($data))
  25. {
  26. $cacheData = array_column($data,'name','id');
  27. $cache->set(Yii::$app->params['cacheKey']['characteristic'],$cacheData);
  28. }
  29. }
  30. $resultData = [];
  31. if(is_array($id))
  32. {
  33. $charData = [];
  34. foreach ($cacheData as $key=>$val)
  35. {
  36. if(in_array($key,$id))
  37. {
  38. $charData[$key] = $val;
  39. }
  40. }
  41. if(!empty($charData) && count($charData)>$num)
  42. {
  43. $rand = array_rand($charData,3);
  44. $resultData[] = $cacheData[$rand[0]];
  45. $resultData[] = $cacheData[$rand[1]];
  46. $resultData[] = $cacheData[$rand[2]];
  47. }
  48. else
  49. {
  50. $resultData = $charData;
  51. }
  52. }
  53. return $resultData;
  54. }
  55. }