[英]Yii2 associative array
我有一個查詢,我從中得到一個數組。
$mData = \Yii::$app->db->createCommand("SELECT s.slab_start, s.slab_end, s.rate, r.cust_id
FROM mdc_tariff_slabs s
INNER JOIN mdc_meter_cust_rel r ON s.t_id = r.tariff_id
WHERE r.cust_id = $consumer_no")->queryAll();
通過var_dump($mData)
我得到
array(3) { [0]=> array(3) { ["slab_start"]=> string(1) "1" ["slab_end"]=> string(3) "100" ["rate"]=> string(2) "10" } [1]=> array(3) { ["slab_start"]=> string(3) "101" ["slab_end"]=> string(3) "150" ["rate"]=> string(2) "12" } [2]=> array(3) { ["slab_start"]=> string(3) "151" ["slab_end"]=> NULL ["rate"]=> string(2) "14" } }
實際上,我希望上面的數組如下所示
[100 => 10, 150 => 12, PHP_INT_MAX => 14];
100
以上是第一個slab_end
, 10
是該值的比率。 150
是第二個slab_end
和它的rate
。 最后一個slab_end 將始終為空/NULL,所以在這種情況下,我輸入PHP_INT_MAX
。 將有N
個slab_end 和rates。
更新 1 MDC 表 Model
class MdcTariffSlabs extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'mdc_tariff_slabs';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['slab_name', 'slab_start', 'rate'], 'required'],
[['slab_start', 'slab_end', 't_id'], 'integer'],
[['slab_name', 'rate'], 'string', 'max' => 50],
[['t_id'], 'exist', 'skipOnError' => true, 'targetClass' => MdcTariff::className(), 'targetAttribute' => ['t_id' => 'id']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Primary Key',
'slab_name' => 'Slab Name',
'slab_start' => 'Start',
'slab_end' => 'End',
'rate' => 'Rate',
't_id' => 'Tariff ID',
];
}
/**
* Gets query for [[T]].
*
* @return \yii\db\ActiveQuery
*/
public function getT()
{
return $this->hasOne(MdcTariff::className(), ['id' => 't_id']);
}
}
你可以這樣做:
$data = MdcTariffSlabs::find()
->joinWith(['t'])
->where('T_TABLE_NAME.cust_id' => $consumer_no)
->all();
//然后map你的數據
$array = ArrayHelper::map($data, 'slab_end', 'rate');
文檔: 構建地圖
//輸出應該是這樣的
[100 => 10, 150 => 12, ...];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.