PHP将值从多维数组转换为数组

时间:2016-04-03 15:55:20

标签: php arrays multidimensional-array

我从$ json_a = json_decode($ filecontent,true)获取一个数组:

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);

非常感谢

3 个答案:

答案 0 :(得分: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"
    }
}

答案 1 :(得分: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
    )

)

希望这有帮助。

答案 2 :(得分:0)

你可以试试。对于像这样的get数组reset($youArr);

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

如何使用数组不知道密钥?