2016-12-28 107 views
-2

我有以下数组。从数组创建数组

{#11950 
    +"attributes": array:3 [ 
    0 => {#608 
     +"attribute_value": "test123" 
     +"attribute_name": "name" 
    } 
    1 => {#556 
     +"attribute_value": "foo moo" 
     +"attribute_name": "lastname" 
    } 
    2 => {#605 
     +"attribute_value": "sample moo" 
     +"attribute_name": "email" 
    } 
    3 => {#606 
     +"attribute_value": "holo" 
     +"attribute_name": "adress" 
    } 
    ] 
} 

我想它转换喜欢跟着

$a = array(
    'name' => 'test123', 
    'lastname' => 'foo moo', 
    'email' => 'sample moo', 
    'address' => 'holo 
); 

我会做同样的操作了无数时间,所以我认为应该有一个适当的解决方案,而随后循环的所有值,并如果其他检查出ATTRIBUTE_NAME等

+1

'array_column()'就足够了。 – mario

+0

您需要遍历所有项目以将其全部转换。不管这是你写的循环,还是使用array_map https://secure.php.net/manual/en/function.array-map.php,你仍然需要触摸每个项目。解决方案将至少O(n) – easement

+0

我不明白你的数组符号。什么是“#11950”,属性名称前面的“+”是什么意思? – Barmar

回答

3

你可以这样做与单个呼叫到array_column,通过使用$index_key参数:

$arr = [ 
    ['attribute_name' => 'foo', 'attribute_value' => 123], 
    ['attribute_name' => 'bar', 'attribute_value' => 456], 
    ['attribute_name' => 'baz', 'attribute_value' => 789], 
]; 

$result = array_column($arr, 'attribute_value', 'attribute_name'); 

https://eval.in/705641参见

0

你可以做一个简单的foreach循环和构建结果数组:)

$result = []; 
foreach ($array as $attr) { 
    $result[$attr['attribute_name']] = $attr['attribute_value']; 
} 

这读起来好一点。它可能不会使在大多数情况下太大的不同,但我不认为这只是一个简单的foreach为高性能;)

$result = array_combine(
    array_column($array, 'attribute_name'), 
    array_column($array, 'attribute_value') 
); 
+0

哦,@Fyntasia打败了我的替代版本^^ – martindilling

0

短暂而简单:

$result = array_combine(array_column($arr, 'attribute_name'), array_column($arr, 'attribute_value'));