PHP code example of phpno1 / dictionary
1. Go to this page and download the library: Download phpno1/dictionary library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
phpno1 / dictionary example snippets
composer
php artisan vendor:publish --provider "Phpno1\Dictionaries\Providers\DictionaryProvider"
'providers' => [
Phpno1\Dictionaries\Providers\DictionaryProvider::class,
]
namespace App;
use Illuminate\Database\Eloquent\Model;
use Phpno1\Dictionaries\Supports\Mapping;
class Goods extends Model
{
use Mapping;//引入trait
}
//config/dictionaries.php
return [
'label'=>'label'//这里是多字段映射用到的
'tags'=>[
'1'=>'进口食品',
'2'=>'奶制品',
],
'recommend'=>[
'1'=>'是',
'2'=>'否',
]
];
/**
* @param string $fields
* @param string $separator 默认值 ,分割方式
* @return string
*/
mapping('字段',"分割方式='默认是 , '");
/**
* @param string $fields
* @param string $separator 默认值 ,分割方式
* @return array
*/
mappings('字段',"分割方式='默认是 , '");
/**
* @param array $fields
* @param string $separator 默认值 ,分割方式
* @return $this
*/
mappings('字段',"分割方式='默认是 , '");
/**
* @param array $fields
* @param string $separator 默认值 ,分割方式
* @return $this
*/
mappingsArray('字段',"分割方式='默认是 , '");
//单条数据转化
Route::get('/', function () {
$result=(new \App\Goods)->first();
//原始数据
array:4 [▼
"id" => 1
"name" => "测试商品"
"tags" => "1,2,3" //或者 ['1',2','3']
"recommend" => "1"
]
//转化 返回字符串
$result->tags_title=$result->mapping('tags');
$result->recommend_title=$result->mapping('recommend');
//转化后数据
array:6 [▼
"id" => 1
"name" => "测试商品"
"tags" => "1,2,3"
"recommend" => "1"
"tags_title" => "进口食品,奶制品"
"recommend_title" => "是"
]
//转化 返回数组
$result->tags_title=$result->mappingArray('tags');
$result->recommend_title=$result->mappingArray('recommend');
//转化后数据
array:6 [▼
"id" => 1
"name" => "测试商品"
"tags" => "1,2,3"
"recommend" => "1"
"tags_title" => array:2 [▼
1 => "进口食品"
2 => "奶制品"
]
"recommend_title" => array:1 [▼
1 => "是"
]
]
});
Route::get('/', function () {
$result=(new \App\Goods)->all();
$result->transform(function($goods){
$goods->tags_title=$goods->mapping('tags');
$goods->recommend_title=$goods->mapping('recommend');
return $goods;
});
dd($result->toArray());
});
$result=(new \App\Goods)->paginate();
$result->getCollection()->transform(function($goods){
$goods->tags_title=$goods->mapping('tags');
$goods->recommend_title=$goods->mapping('recommend');
return $goods;
});
dd($result->toArray());
Route::get('/', function () {
$result=(new \App\Goods)->first();
//转化 返回字符串
$result=$result->mappings(['tags','recommend']);
dd($result->toArray());
//转化 返回数组
$result=$result->mappingsArray(['tags','recommend']);
dd($result->toArray());
});