Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

Loop through 2 arrays containing array and array of objects - Php

I have Array called ArrayObj as below,

ArrayObj = [
{
  "attr1" : "d1",
  "attr2" : "some data for d1 key"
  ...
},
{      
  "attr1" : "d2",
  "attr2" : "some data for d2 key"
  ...
},
.
.
. 33 objects
]

whose values are same after every N objects. here let's say, after 11 items.

using above ArrayObj I created Array1 as below:

Array1 = ["d1","d2","d3",...,"d1","d2","d3",...,"d1","d2","d3",...33 items]

because it contains same value after every N values I get something as above.

Now, I would like to create Array2 by looping through Array1 one time which contains 33 items and ArrayObj one time which has 33 objects and merge them but into 3 objects only.

because 33 items (Array1 : left hand side key) = 33 items (ArrayObj : right hand side value) remember I need only values for a single attribute from ArrayObj

but the issue or the challenge here is that the key for all three newly created objects are the same and so it overwrites and I end-up with only 1 object inside an array.

What I am looking for is below:

[
{
      "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
}
]

What I get is:

[
{
      "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
}
]

Code

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

Upvotes: 2

Views: 63

Answers (1)

splash58
splash58

Reputation: 26153

Use array_chunk to split your array to groups with 3 objects a group

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

demo

Upvotes: 1

Related Questions