Heim > Fragen und Antworten > Hauptteil
[0]=>
array(5) {
["id"]=>
string(1) "2"
["title1"]=>
string(6) "颜色"
["content1"]=>
string(4) "红2"
["title2"]=>
string(6) "尺码"
["content2"]=>
string(2) "XL"
}
[1]=>
array(5) {
["id"]=>
string(1) "1"
["title1"]=>
string(6) "颜色"
["content1"]=>
string(4) "红1"
["title2"]=>
string(6) "尺码"
["content2"]=>
string(1) "L"
}
[2]=>
array(5) {
["id"]=>
string(1) "3"
["title1"]=>
string(6) "颜色"
["content1"]=>
string(4) "红3"
["title2"]=>
string(6) "尺码"
["content2"]=>
string(3) "XXL"
}
拼装成这样
array(5) {
["title1"]=>
string(6) "颜色"
["content1"]=>
array(5) {
["id"]=>
string(1) "2"
["content1"]=>
string(4) "红2"
["id"]=>
string(1) "1"
["content1"]=>
string(4) "红1"
["id"]=>
string(1) "3"
["content1"]=>
string(4) "红3"
}
["title2"]=>
string(6) "尺码"
["content2"]=>
array(5) {
["id"]=>
string(1) "2"
["content2"]=>
string(4) "XL"
["id"]=>
string(1) "1"
["content2"]=>
string(4) "L"
["id"]=>
string(1) "3"
["content2"]=>
string(4) "XXL"
}
}
phpcn_u15822017-05-16 13:09:30
题主的想要拼装的部分有问题,以content1
为例:
['content1'] => [
'id'=>2,
'content1'=>'红2',
'id'=>1,
'content1'=>'红1',
'id'=>3,
'content1'=>'红3',
]
这样最终只能保留id为3的数据。
我猜题主应该需要的是这样:
['content1'] => [
['id'=>2,'content1'=>'红2'],
['id'=>1,'content1'=>'红1'],
['id'=>3,'content1'=>'红3'],
]
那么,“史上最垃圾的写法来啦”,建议题主自己跑一下下面的代码。
原始数组:
$arr = [
['id'=>2,'title1'=>'颜色','content1'=>'红2','title2'=>'尺码','content2'=>'XL'],
['id'=>1,'title1'=>'颜色','content1'=>'红1','title2'=>'尺码','content2'=>'L'],
['id'=>1,'title1'=>'颜色','content1'=>'红3','title2'=>'尺码','content2'=>'XXL']
];
我写的代码:
$newArr = [];
foreach($arr as $k=>$v)
{
$keyArr = array_keys($v);
$valueArr = array_values($v);
foreach($keyArr as $key=>$val)
{
if((strstr($val, 'title') || strstr($val, 'content')) && !array_key_exists($val, $newArr))
$newArr[$val] = strstr($val, 'title') ? $valueArr[$key] : [];
if(strstr($val, 'content'))
{
foreach($arr as $ke=>$va)
{
$newArr[$val][$ke]['id'] = $va['id'];
$newArr[$val][$ke][$val] = $va[$val];
}
}
}
}
不才,代码写的不好,还望题主见谅,大神别打我脸。