Array
(
[0] => Array
(
[Handle] => example-t-shirt
[Title] => Example T-Shirt
[Vendor] => Acme
[Type] => Shirts
)
[1] => Array
(
[Handle] => example-t-shirt
[Title] => 1
[Vendor] => 2
[Type] => 3
)
[2] => Array
(
[Handle] => example-t-shirt
[Title] => 4
[Vendor] => 5
[Type] => 6
)
)
我有这个数组,我想转换它像
Array
(
[Handle] => example-t-shirt,example-t-shirt,example-t-shirt
[Title] => Example T-Shirt,1,4
[Vendor] => Acme,2,5
[Type] => Shirts,3,6
)
像句柄或标题这样的数组的更多关键也没有修复,这些也是动态的。 提前谢谢
答案 0 :(得分:1)
首先需要将其生成为数组:
<?php
$mainArray = array(
array(
"Handle" => "example-t-shirt",
"Title" => "Example T-Shirt",
"Vendor" => "Acme",
"Type" => "Shirts"
),
array(
"Handle" => "example-t-pant",
"Title" => "Example T-Pant",
"Vendor" => "Meca",
"Type" => "Pants"
)
);
$finalArray = array(
"Handle" => array(),
"Title" => array(),
"Vendor" => array(),
"Type" => array()
);
foreach ($mainArray as $current)
foreach ($current as $key => $value)
$finalArray[$key][] = $value;
?>
之后,$finalArray
中的每一个都应加入。
foreach ($finalArray as $key => $value)
$finalArray[$key] = implode(", ", $value);
所以你的最终代码将是:
<?php
$mainArray = array(
array(
"Handle" => "example-t-shirt",
"Title" => "Example T-Shirt",
"Vendor" => "Acme",
"Type" => "Shirts"
),
array(
"Handle" => "example-t-pant",
"Title" => "Example T-Pant",
"Vendor" => "Meca",
"Type" => "Pants"
)
);
$finalArray = array(
"Handle" => array(),
"Title" => array(),
"Vendor" => array(),
"Type" => array()
);
foreach ($mainArray as $current)
foreach ($current as $key => $value)
$finalArray[$key][] = $value;
foreach ($finalArray as $key => $value)
$finalArray[$key] = implode(", ", $value);
?>
<强>输出强>
Array
(
[Handle] => example-t-shirt, example-t-pant
[Title] => Example T-Shirt, Example T-Pant
[Vendor] => Acme, Meca
[Type] => Shirts, Pants
)
答案 1 :(得分:0)
这是一个使用array_walk_recursive
的工作示例$mainArray = array(
array(
"Handle" => "example-t-shirt",
"Title" => "Example T-Shirt",
"Vendor" => "Acme",
"Type" => "Shirts"
),
array(
"Handle" => "example-t-pant",
"Title" => "Example T-Pant",
"Vendor" => "Meca",
"Type" => "Pants"
)
);
$final = array();
array_walk_recursive($mainArray, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item .', '. $final[$key] : $item;
});
var_dump($final);
答案 2 :(得分:0)
试试这个:
<?php
$temp = array(
array(
"Handle" => "example-t-shirt",
"Title" => "Example T-Shirt",
"Vendor" => "Acme",
"Type" => "Shirts"
),
array(
"Handle" => "example-t-shirt",
"Title" => 1,
"Vendor" => 2,
"Type" => 3
),
array(
"Handle" => "example-t-shirt",
"Title" => 4,
"Vendor" => 5,
"Type" => 6
)
);
$result = array();
foreach($temp as $t){
if (is_array($t)){
foreach ($t as $k=>$r){
if(array_key_exists($k,$result)){
$result[$k] .= ','.$r;
} else {
$result[$k] = $r;
}
}
}
}
echo '<pre>';
print_r($result);
?>