D
D
Dmitry Kim2016-03-28 11:16:50
Yii
Dmitry Kim, 2016-03-28 11:16:50

What's wrong with ArrayHelper::index YII2?

Here www.yiiframework.com/doc-2.0/guide-helper-array.ht... it is said about the possibility of grouping an array so that from:

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];

you can get it:
$array = [
    '123' => [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
    ],
    '345' => [ // all elements with this index are present in the result array
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ]
]

In reality, this does not happen. Where did such documentation come from? Perhaps they mixed up the names of the methods?
In particular:
$a = [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ];

    $b = yii\helpers\ArrayHelper::index($a, null, 'id');

    var_dump($b);

issues
array (size=1)
  '' => 
    array (size=3)
      'id' => string '345' (length=3)
      'data' => string 'hgi' (length=3)
      'device' => string 'smartphone' (length=10)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kim, 2016-03-29
@kimono

The question is closed. Apparently this is an error in the documentation. It's a pity, the functionality is necessary.

M
mitaichik, 2016-03-28
@mitaichik

Everything works fine, something is wrong with your code. Maybe publish it - prompt in detail.

A
Anton Natarov, 2016-03-28
@HanDroid

Everything is working. The current that I checked in the controller

public function actionToggle()
    {
        $a = [
            ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
            ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
            ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
        ];

        $b = ArrayHelper::index($a, 'id');

        return $this->render('toggle', [
            'b' => $b,
        ]);
    }

in View toggle
<?php
/* @var $this yii\web\View */

$this->title = 'Ars';
?>

<h1>Привет</h1>

<?php
echo "<pre>";
var_dump($b);
?>

an array of this format has become
array(2) {
  [123]=>  array(3) {
    ["id"]=>    string(3) "123"
    ["data"]=>    string(3) "abc"
    ["device"]=>    string(6) "laptop"
  }
  [345]=>
  array(3) {
    ["id"]=>    string(3) "345"
    ["data"]=>    string(3) "hgi"
    ["device"]=>    string(10) "smartphone"
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question