2016-04-03 29 views
2

我越來越從$ json_a = json_decode數組($ filecontent,真):PHP打開值到一個數組

Array (
     [meta_titles] => Array ( 
       [0] => Just another site 
       [1] => Test test 
       [2] => This is a test 
     ) 
     [tag_titles] => Array ( 
       [0] => Test 1 
       [1] => Value 2 
       [2] => String 3 
     ) 
) 

我想修改數組如下:

Array (
     [meta_titles] => Array ( 
       Just another site => Just another site 
       Test test => Test test 
       This is a test => This is a test 
     ) 
     [tag_titles] => Array ( 
       Test 1 => Test 1 
       Value 2 => Value 2 
       String 3 => String 3 
     ) 
    ) 

因此,數值成爲關鍵。有人會有想法嗎?

編輯:到目前爲止我的代碼:

$json_a = json_decode($filecontent, true); 

$newjson = array(); 
foreach($json_a as $category) { 
    $newjson[$category] = array_combine(array_values($category), $category); 
}       
$json = json_encode($newjson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); 

非常感謝

+0

EUH你的鏈接使我對「什麼是‘1’在一個PHP的print_r語句的結束意味着?」這與問題無關。 – scrybs

+0

Wups是的,不知何故,我沒有複製正確的鏈接。我的意思是這一個:http://stackoverflow.com/q/5422955/3933332只是使用相同的子數組的鍵和值。 – Rizier123

回答

3

使用array_combinearray_values功能的解決方案。在地點標記與&改變數組值作爲參考:

$json = [ 
    'meta_titles' => [ 0 => 'Just another site' , 1 => 'Test test' , 2 => 'This is a test'], 
    'tag_titles' => [ 0 => 'Test 1' , 1 => 'Value 2' , 2 => 'String 3']  
]; 

foreach($json as &$category) { 
    $category = array_combine(array_values($category), $category); 
} 

$json = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); 

print_r($json); 

輸出:

{ 
    "meta_titles": { 
     "Just another site": "Just another site", 
     "Test test": "Test test", 
     "This is a test": "This is a test" 
    }, 
    "tag_titles": { 
     "Test 1": "Test 1", 
     "Value 2": "Value 2", 
     "String 3": "String 3" 
    } 
} 
+0

meta_titles是動態的,但其中還有其他數組名...我應該在foreach循環中執行它? – scrybs

+1

根據這個條件更新你的問題「裏面還有其他的數組名稱」,更新預期的輸出,我會爲你的 – RomanPerekhrest

+0

完成我的解決方案!謝謝 – scrybs

0

試試這個:

$array = array (
    'meta_titles' => array ( 
      0 => 'Just another site', 
      1 => 'Test test' , 
      2 => 'This is a test' 
    ) 
); 

$new_array['meta_titles'] = array(); 

foreach($array['meta_titles'] as $v) { 
    $new_array['meta_titles'][$v] = $v; 
} 
echo "<pre>"; 
print_r($new_array); 

這給:

Array 
(
[meta_titles] => Array 
    (
     [Just another site] => Just another site 
     [Test test] => Test test 
     [This is a test] => This is a test 
    ) 

) 

希望這有助於。

+0

感謝您的回答。 meta_title應該是動態的,但...我想:的foreach($ json_a爲$類){ \t的foreach($類別爲$字符串){\t \t \t \t \t \t \t \t \t $ json_a [$類] [ $ string] = $ string; \t}但它不會改變密鑰... \t} – scrybs

0

您可以試試。 reset($youArr);爲GET數組這樣

{ 
    Array { 
      0 =》title 
      1=》 description 
      2 =》keywords 
      } 
} 

而如何可以使用數組不知道鑰匙?

+0

密鑰應該等於值key => key。所以json編碼返回「Value」:「Value」。 – scrybs

+0

@GuilVll如果返回0,1,2。我可以使用這個jast'res [0]'如果value = value我需要使用循環來獲取每個元素... – Naumov

相關問題