Home > OS >  How to add object after every N indexes in array of objects in PHP?
How to add object after every N indexes in array of objects in PHP?

Time:01-27

I want to add new Item after every 3 indexes.

$mainArr = '[
    {"name":"Saqib1", "id":"1"},
    {"name":"Saqib2", "id":"2"},
    {"name":"Saqib3", "id":"3"},
    {"name":"Saqib4", "id":"4"},
    {"name":"Saqib5", "id":"5"},
    {"name":"Saqib6", "id":"6"},
    {"name":"Saqib7", "id":"7"},
    {"name":"Saqib8", "id":"8"},
    {"name":"Saqib9", "id":"9"},
    {"name":"Saqib10", "id":"10"}
]';


// Initial array of objects
$newObject = new stdClass(); // The new object you want to add

$newObject->name = 'New';
$newObject->id = '11';
$newObject->extraKey = 'this is extra key for newObjects to identify';

$n = 3; // The number of indexes after which to add the new object

$decoded = json_decode($mainArr);

for ($i = 0; $i < count($decoded); $i  ) {
     
    if (($i   1) % $n == 0) {
        array_splice($decoded, $i, 0, $newObject);
    }
}

print_r($mainArr);

Error:

PHP Warning: count(): Parameter must be an array or an object that implements Countable.

I tried json_decode still not working.

UPDATE: The valid json issue resolved as indicated in comments.

CodePudding user response:

It would probably make more sense to do this by creating a new array and adding items to it at the right time

e.g.

$mainArr = '[
    {"name":"Saqib1", "id":"1"},
    {"name":"Saqib2", "id":"2"},
    {"name":"Saqib3", "id":"3"},
    {"name":"Saqib4", "id":"4"},
    {"name":"Saqib5", "id":"5"},
    {"name":"Saqib6", "id":"6"},
    {"name":"Saqib7", "id":"7"},
    {"name":"Saqib8", "id":"8"},
    {"name":"Saqib9", "id":"9"},
    {"name":"Saqib10", "id":"10"}
]';


// Initial array of objects
$newObject = new stdClass(); // The new object you want to add

$newObject->name = 'New';
$newObject->id = '11';
$newObject->extraKey = 'this is extra key for newObjects to identify';

$n = 3; // The number of indexes after which to add the new object
$newArr = [];

$decoded = json_decode($mainArr);

for ($i = 0; $i < count($decoded); $i  ) {
     $newArr[] = $decoded[$i];
     
    if (($i   1) % $n == 0) {
        $newArr[] = $newObject;
    }
}

var_dump($newArr);

Demo: https://3v4l.org/ErQe7

  • Related