PHP没有foreach操作数组

Would anyone happen to know if there is an even more efficient way or single function that will achieve the below without the need for a foreach loop? I understand that it will have practically no performance issue on the below however I'm always looking for new and hopefully more efficient ways to code.

(Push first element value to key, push second element value to new key value, unset old data)

Input

Array
(
    [0] => Array
        (
            [supplier_id] => 1
            [supplier_company] => Company Alpha
        )

    [1] => Array
        (
            [supplier_id] => 2
            [supplier_company] => Company Beta
        )

)

Function

foreach ($suppliers as $key => $value) {
      $new_array[$value['supplier_id']] = $value['supplier_company'];
}

Output

Array
(
    [1] => Company Alpha
    [2] => Company Beta
)

array_column will do the trick:

$inp = array(
    array(
        'supplier_id' => 1,
        'supplier_company' => 'Company Alpha'
    ),array(
        'supplier_id' => 2
        'supplier_company' => 'Company Beta'
    )
);

$out = array_column($inp,'supplier_company','supplier_id');

var_dump($out);
/*
Array
(
    [1] => Company Alpha
    [2] => Company Beta
)
*/

If you are using PHP5 >= 5.5.0, you can try array_column as following :

$suppliers = array_column($suppliers, 'supplier_company','supplier_id');
print_r($suppliers);

You may use the function each(), which is available since ever, with the constructor list().

Here is an example:

$a=array(
    array(
        'a'=>0,'b'=>5
    ),
    array(
        'a'=>'no','b'=>'yes'
    )
);

while(list(,$tmp) = each($a))$new_array[$tmp['a']] = $tmp['b'];

var_dump($new_array);

Should output:

array(2) {
  [0]=>
  int(5)
  ["no"]=>
  string(3) "yes"
}

Both methods exist since PHP4, so, you can use them forever.

If you want to squeeze a tiny bit more of performance, you can use pointers:

while(list(,$tmp) = each(&$a))$new_array[$tmp['a']] = &$tmp['b'];

It is safe to use unset($a) after!
This is faster because you are simply assigning a pointer to a memory address, instead of providing a new copy of the array.

You can use anonymous functions:

$arr = array
    (
     0 => array
     (
      'supplier_id' => 3,
      'supplier_company' => 'Company Alpha'
      ),

     1 => array
     (
      'supplier_id' => 4,
      'supplier_company' => 'Company Beta'
      )

     );

     $names = array_map(function ($arg){return array($arg['supplier_id']=>$arg['supplier_company']);}, $arr);

array_column does exactly that, as others have mentioned.

Now, just for fun, you could try something creative like using extract within your foreach loop. Both your IDE and your teammates will squeak at you, through.

foreach($inp as $supplier) {
    extract($supplier);

    // magic variables!
    echo $supplier_id;
    echo $supplier_company;
}