2014-07-12 65 views
-1

我有數組:破滅陣列,普萊舍幫助我

array (
    [name_0] => 'ABC', 
    [price_0] => '5000', 
    [name_1] => 'DEF', 
    [price_1] => 499, 
    [name_n] => 'GHI', 
    [price_n] => 1000 
); 

我想:NAME_0 | NAME_1 | name_n ....和price_0 | PRICE_1 | price_n ....

回答

0

嘗試類似下面

$a = array (
    'name_0' => 'ABC', 
    'price_0' => '5000', 
    'name_1' => 'DEF', 
    'price_1' => 499, 
    'name_n' => 'GHI', 
    'price_n' => 1000 
); 
$arr_name = array(); 
$arr_price = array(); 
foreach($a as $k=>$v){ 
    if (stripos(strtolower($k), 'name') !== false) { 
     $arr_name[$k] = $v; 
    }else{ 
     $arr_price[$k] = $v; 
    } 
} 
$a = array_merge($arr_name, $arr_price); 
$res = implode('|', $a); 
echo $res; 

輸出

ABC|DEF|GHI|5000|499|1000 
0

我會這樣做:

$temp = array_flip($array); 
sort($temp); 
$str = implode("|", $temp); 

這似乎只要工作,只要你想name先出現,如n早在字母表。如果你想在corrensponding值在同一順序內爆,而不是鍵:

ksort($array); 
$str = implode("|", $array); 
2

如果這些都是名稱/價格對,而你想要的價值,你可以利用PHP 5.5的array_column()功能:

$chunked = array_chunk($array, 2); 
$names = array_column(
    $chunked, 
    0 
); 
$names = implode('|', $names); 

$prices = array_column(
    $chunked, 
    1 
); 
$prices = implode('|', $prices); 

如果你正在運行之前版本的PHP:

$chunked = array_chunk($array, 2); 
$names = array_map(
    function ($value) { 
     return $value[0]; 
    }, 
    $chunked 
); 
$names = implode('|', $names); 

$prices = array_map(
    function ($value) { 
     return $value[1]; 
    }, 
    $chunked 
); 
$prices = implode('|', $prices);