Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array to multidimensional array with special keys using php?

I have an array

$array = [
    0=>1 
    1=>Jon 
    2=>[email protected] 
    3=>2 
    4=>Doe 
    5=>[email protected] 
    6=>3
    7=>Foo 
    8=>[email protected]
]

What I`d like to do is to add and extra value to each value. Something like this so I can access it when looping through the array

$array=[
    0=>1[id] 
    1=>Jon[name] 
    2=>[email protected][email] 
    3=>2[id] 
    4=>Doe[name] 
    5=>[email protected][email] 
    6=>3[id] 
    7=>Foo[name] 
    8=>[email protected][email]
]

I guess it would be a multidimensional array? What would be the proper way of doing it?

like image 786
Davis Avatar asked Feb 14 '26 00:02

Davis


1 Answers

Loop through array and check key of items and based of it create new array and insert values in it.

$newArr = [];    
foreach($array as $key=>$value){
    if ($key % 3 == 0)
        $newArr[] = ["id" => $value];
    if ($key % 3 == 1)
        $newArr[sizeof($newArr)-1]["name"] = $value;
    if ($key % 3 == 2)
        $newArr[sizeof($newArr)-1]["email"] = $value;
}

Check result in demo

like image 111
Mohammad Avatar answered Feb 16 '26 15:02

Mohammad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!