2013-07-20 96 views
-1

我正在使用PHP。我有一個數組。我有一個數組。我需要創建類似([CN] => Chinese)這種格式的語言數組。將數組值轉換爲密鑰

我的數組響應如下。

Array 
(
    [0] => stdClass Object 
     (
      [language_name] => Chinese 
      [language_code] => CN 
     ) 

    [1] => stdClass Object 
     (
      [language_name] => English 
      [language_code] => EN 
     ) 

    [2] => stdClass Object 
     (
      [language_name] => Korea 
      [language_code] => KO 
     ) 

    [3] => stdClass Object 
     (
      [language_name] => Vietnamese 
      [language_code] => VN 
     ) 

) 

我需要這種類型的數組

Array(
     [CN]=>Chinese 
     [EN]=>English 
     [KO]=>Korea 
     [VN]=>Vietnamese 
) 

我如何能做到這一點的轉換?

回答

2

代碼:

<?php 

$newArray = array(); 

foreach($yourArray as $key => $items) { 
    $newArray[$items->language_code] = $items->language_name; 
} 

die('<pre>' . print_r($newArray, true) . '</pre>'); 

就是這樣。

0

使用PHP的foreach

function convert($array){ 
    $ret = array(); 

    foreach($array as $obj){ 
     $ret[$obj->language_code] = $obj->language_name; 
    } 

    return $ret; 
} 
0

你可以試試這個:

foreach($objects as $object) 
{ 
    $newArray[$object->language_code] = $object->language_name; 
} 
print_r($newArray); 
0

此代碼工作正常

foreach($objects as $object) 
{ 
    $newArray[$object->language_code] = $object->language_name; 
} 
echo "<pre>"; 
print_r($newArray); 
echo "</pre>";