0

I have two arrays one of them contain a new key name

$assoc = ['name', 'lastname', 'pesel']; 

and second look this

$inputs = ['John', 'Don', '987987', 'Mike', 'Evans', '89779' ];

Array $assoc is the new key name, and I would like to change [0],[1] to ['name'] etc

array(2) {
 ['person'] =>
 array(3) {
 ['name'] => string(4) "John"
 ['lastname'] => string(3) "Don"
 ['pesel'] => string(6) "987987"
 }
 ['person'] =>
 array(3) {
 ['name'] => string(4) "Mike"
 ['lastname'] => string(5) "Evans"
 ['pesel'] => string(5) "89779"
 }
}

Thanks for your help

asked Mar 10, 2013 at 16:05
3
  • 1
    Use array_chunk on your value list, then bind keys to each chunk using array_combine. Commented Mar 10, 2013 at 16:10
  • 2
    You can't have multiple elements in one array that have the same key. The latter will overwrite the former. So array( 'person' => ..., 'person' => ... ) will not be an array with two elements. Commented Mar 10, 2013 at 19:53
  • 1
    yes you have right :) i'm so stupid Commented Mar 10, 2013 at 19:58

2 Answers 2

5

It's pretty simple:

$new_array = array();
foreach(array_chunk($inputs, 3) as $person) {
 $new_array[] = array_combine($assoc, $person);
}
answered Mar 10, 2013 at 16:11

Comments

-1
<?php
$assoc=Array("name", "lastname", "pesel");
$inputs=Array('John', 'Don', '987987', 'Mike', 'Evans', '89779' );
$resultant_array=Array();
for($i=0; $i<count($inputs); $i+=count($assoc)){
//echo $i."\n\n";
 for($j=0; $j<count($assoc); $j++){
 $b2g[$assoc[$j]]=$inputs[$i+$j];
 }
 $resultant_array[]=$b2g;
} 
print_r($resultant_array);

It is a more lengthy and general purpose use.. I actually have used much recurssions..

answered Mar 10, 2013 at 16:21

2 Comments

Weird that you preferred this answer to mine... I assume you like things cluttery.
No. I like exploring with code rather looking for it on Google.. both takes same time

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.