取出平坦阵列中所有字符串的前缀并将其用作钥匙,然后按键排序 我有这个数组: 大批 (( 0 =>“ 3_some val”, 1 =>“ 1_some其他val”, 2 =>“ 0_val”, 3 =>“ 2_value”, 4 ...

问题描述 投票:0回答:1
考虑上述数组,是否有这样的方法可以做到这样的数组?

Array ( 0 => "val", 1 => "some other val", 2 => "value", 3 => "some val", 4 => "other value" )

实际上迫使强调的数字是新创建的数组中的密钥。
    

this应该这样做:

(_)

$arr1 = array (
  0 => "3_some val",
  1 => "1_some other val",
  2 => "0_val",        
  3 => "2_value",
  4 => "4_other value"
);

$result = array();

foreach($arr1 as $val) {
    list($key, $value) = explode('_', $val, 2);
    $result[$key] = $value;
}

// Sort by keys
ksort($result);
将打印出来:

php arrays associative-array
1个回答
5
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.