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
konadriankonadrian
asked Mar 10, 2013 at 16:05
2 Answers 2
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
<?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
lang-php
array_chunk
on your value list, then bind keys to each chunk usingarray_combine
.array( 'person' => ..., 'person' => ... )
will not be an array with two elements.