我有一个名为ArrayObj的Array,如下所示,
ArrayObj = [
{
"attr1" : "d1",
"attr2" : "some data for d1 key"
...
},
{
"attr1" : "d2",
"attr2" : "some data for d2 key"
...
},
.
.
. 33 objects
]
每N个对象后的值相同。这里可以说是11件事之后。
使用上面的ArrayObj我创建了Array1,如下所示:
Array1 = ["d1","d2","d3",...,"d1","d2","d3",...,"d1","d2","d3",...33 items]
因为它在每N个值之后包含相同的值,我得到的内容如上所述。
现在,我想通过循环遍历Array1一次创建Array2,其中包含33个项目和ArrayObj,一次有33个对象并将它们合并为3个对象。
因为33项(Array1:左侧键)= 33项(ArrayObj:右侧值)请记住我只需要来自ArrayObj的单个属性的值
但是这里的问题或挑战是所有三个新创建的对象的键是相同的,因此它会被覆盖,最终只有一个数组内的对象。
我正在寻找的是:
[
{
"d1" : "some data 1",
"d2" : "some data 2",
"d3" : "some data 3",
...
...
11 objects
},
{
"d1" : "some data 1",
"d2" : "some data 2",
"d3" : "some data 3",
...
...
11 objects
},
{
"d1" : "some data 1",
"d2" : "some data 2",
"d3" : "some data 3",
...
...
11 objects
}
]
我得到的是:
[
{
"d1" : "some data 1", //The Last object only, first 2 are overwritten because of same keys
"d2" : "some data 2",
"d3" : "some data 3",
...
...
11 objects
}
]
$ArrayObj (contains 33 objects with all the data)
$Array1 = array(); // 33 items
$Array2 = array(); // new array need to add 3 objects
for($j = 0; $j < $totalCount; $j++){ //33 totalCount
$Array1[$j] = $ArrayObj[$j]['left_side_data']; //getting particular attribute value and storing it as an array
}
//By now I have $Array1 with 33 items in it containing all the items which will be keys for Array2
foreach($ArrayObj as $key=>$res){
$Array2[$Array1[$key]] = $ArrayObj[$key]['data'];
}
return $Array2;
答案 0 :(得分:1)
使用array_chunk将数组拆分为具有3个对象组的组
$ArrayObj = json_decode($ArrayObj, true);
$temp = array_chunk($ArrayObj, 3);
$res = [];
foreach (array_chunk($ArrayObj, 2) as $items) {
$temp = [];
foreach($items as $x) {
$temp[$x["attr1"]] = $x["attr2"];
}
$res [] = $temp;
}
print_r(json_encode($res));