Friday, 31 August 2018

PHP - How can I make an associative array from two offsets of a normal array?

I have an array of paired values (name, and email) and I'm trying to make an associative array from a normal array for every two offsets. Example:

Array
 (
    [0] => joe
    [1] => joe@gmail.com
    [2] => bill
    [3] => bill@gmail.com
    [4] => kyle
    [5] => kyle@gmail.com
    [6] => matt
    [7] => matt@gmail.com
    [8] => chris
    [9] => chris@gmail.com
)

I would like to make an associative array for each [$i] & [$i+1], so it would look like:
Array
 (
    [0] => Array
        (
            [name] => joe
            [email] => joe@gmail.com
        )
    [1] => Array
        (
            [name] => bill
            [email] => bill@gmail.com
        )
 )

I tried :
$num = count($csvArray);
for ($i=0; $i < $num; $i+2) {
    $newArray[] = array(
        'name' => $csvArray[$i],
        'email' => $csvArray[$i+1]
    );
}

It gives me this error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in C:\xampp\htdocs\array.php on line 20
Am I doing something wrong?

there is a problem in your for loop... it should be
for($i=0; $i < $num; $i=$i+2)

currently it's not getting incremented and hence the infinite loop

0 comments:

Post a Comment