Skip to content

Instantly share code, notes, and snippets.

@k1ic
Created September 20, 2015 11:09
Show Gist options
  • Save k1ic/56daf627ed43718f69bf to your computer and use it in GitHub Desktop.
Save k1ic/56daf627ed43718f69bf to your computer and use it in GitHub Desktop.
php array_walk vs foreach
<?php
$arr0 = array(
'aa' => array(
'aa_1' => array('value' => 1, 'name' => 'aa1'),
'aa_2' => array('value' => 2, 'name' => 'aa2'),
'aa_3' => array('value' => 3, 'name' => 'aa3'),
),
'ab' => array(
'ab_1' => array('value' => 4, 'name' => 'ab1'),
),
'ac' => array(
'ac_1' => array('value' => 5, 'name' => 'ac1'),
),
);
$arr1 = array(
'aa_1' => array('value' => 1, 'name' => 'aa1'),
'aa_2' => array('value' => 2, 'name' => 'aa2'),
'aa_3' => array('value' => 3, 'name' => 'aa3'),
'ab_1' => array('value' => 4, 'name' => 'ab1'),
'ac_1' => array('value' => 5, 'name' => 'ac1'),
);
//将$arr0变为$arr1
//法1 foreach
foreach (array_values($arr0) as $k => $v)
{
$k == 0 && $tmp = $v;
$tmp = array_merge($tmp, $v);
}
foreach ($tmp as $v)
{
$arr1[$v['value']] = $v['name'];
}
//法2 array_walk
$arr1 = array();
array_walk($arr0, function($items, $key){ global $arr1; $arr1 = $arr1+$items; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment