There is a table in the database (site settings):

+----+-------+--------+ | id | name | value | +----+-------+--------+ | 1 | test1 | value1 | | 2 | test2 | value2 | +----+-------+--------+ 

I select the lines (I work with Yii2) and get the following array:

 Array ( [0] => Array ( [name] => test1 [value] => value1 ) [1] => Array ( [name] => test2 [value] => value2 ) ) 

I want to get the following (for ease of use):

 Array ( [test1] => value1 [test2] => value2 ) 

I went this way:

 $prettyResult = []; foreach ($initialResult as $value) { $prettyResult[$value['name']] = $value['value']; } 

However, something tells me that it is somehow clumsy and the plan can be implemented more elegantly using native functions or SQL (or Yii2)?

Lately, almost everywhere, where I meet array brute force, it seems clumsy ...

  • one
    In short, the three lines of the solution most likely will not be. You can do it through array_combine, two array_map and lambdas, but there's no sense in it. - etki
  • @Etki, found one :) - Roman Grinyov

2 answers 2

Perhaps the array_column() function will help you:

 array_column($array, 'value', 'name'); 

Before:

 Array ( [0] => Array ( [name] => test1 [value] => value1 ) [1] => Array ( [name] => test2 [value] => value2 ) ) 

After:

 Array ( [test1] => value1 [test2] => value2 ) 

You can check here

  • man: php.net/array-column ... damn, it looked the same, but it was so important to figure out how it works ... let this comment be a reminder lesson for me and for those who do not read the documentation on the function / method / etc to the end :) - Roman Grinyov
  • one
    For me it was unexpected, by the way, that my first answer was for you. We met before, but only on a different project and you helped me. The world is small, as they say) - Semushin Sergey
  • Oh, we will meet more than once in the open spaces of development, and maybe we will work together :) - Roman Grinyov
  • Good sandbox (not only in PHP): repl.it/CuHQ ... - Roman Grinyov
  • Oh, thanks, but I took the first one I got - Semushin Sergey

The yii\helpers\ArrayHelper::map() method can help you.

Signature:

 public static array map ( $array, $from, $to, $group = null ) 

As $from , specify the name , and as $to - value .


Example:

 $array = [ ['name' => 'test_name_1', 'email' => 'test_email_1'], ['name' => 'test_name_2', 'email' => 'test_email_2'], ]; $result = \yii\helpers\ArrayHelper::map($array, 'name', 'email'); echo '<pre>'; print_r($result); echo '</pre>'; // Array // ( // [test_name_1] => test_email_1 // [test_name_2] => test_email_2 // )