Search code examples
phparraysyii2-advanced-app

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

By var_dump($mData) I am getting

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]; 

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.

Update 1 MDC Table 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']);
}
}

Solution

  • You can do something like this:

    $data = MdcTariffSlabs::find()
       ->joinWith(['t'])
       ->where('T_TABLE_NAME.cust_id' => $consumer_no)
       ->all();
    

    //Then map your data

    $array = ArrayHelper::map($data, 'slab_end', 'rate');
    

    Documentation: Building Maps

    //Output should be like this

    [100 => 10, 150 => 12, ...];