Yii2关联数组 [英] Yii2 associative array
问题描述
我有一个要从中获取数组的查询。
I have a query from which I am getting an 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 }}
实际上,我希望将上面的数组变成下面的
In actual I want the above array into like below
[100 => 10, 150 => 12, PHP_INT_MAX => 14];
100
以上是第一个 slab_end
和 10
是该值的汇率。 150
是第二个 slab_end
,它是费率
。最后一个slab_end始终为空/ NULL,因此,在这种情况下,我要放置 PHP_INT_MAX
。 slab_end和费率的数字将为 N
。
Above 100
is the first slab_end
and 10
is the rate of that value. 150
is the second slab_end
and along with it's rate
. The last slab_end will always be empty/NULL so in that case, I am putting PHP_INT_MAX
. There will be N
number of slab_end and rates.
更新1个MDC表模型
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();
//然后映射数据
$array = ArrayHelper::map($data, 'slab_end', 'rate');
文档:构建地图
//输出应该像这样
[100 => 10, 150 => 12, ...];
这篇关于Yii2关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!