I want to make a new array by specify key
For example I have an array:
$data = [
0 => 'name',
1 => '29',
2 => '7/26 City Avenue',
]
And I want to make new array like this
$data = [
'name' => 'name',
'age' => '29',
'address' => '7/26 City Avenue',
]
How to make new array like above example ?
Please try this
<?php
$keylabel=array("name","age","address");
$data=array("name","29","7/26 City Avenue");
$data_keylabel=array_combine($keylabel,$data);
print_r($data_keylabel);
?>
<?php
$data = [
0 => 'name',
1 => '29',
2 => '7/26 City Avenue',
];
$data['name'] = $data[0];
unset($data[0]);
$data['age'] = $data[1];
unset($data[1]);
$data['address'] = $data[2];
unset($data[2]);
print_r($data);
This is an example. Your new array has the keys set in the way you want.
The simplest but NOT cleanesr solution would be parsing it into a new array like
$data_new = [];
$data_new['name'] = $data[0];
$data_new['age' = $data[1];
$data_new['address'] = $data[2];
Cleaner would be array_combine
Example from the reference Link
$a = array('gruen', 'rot', 'gelb');
$b = array('avokado', 'apfel', 'banane');
$c = array_combine($a, $b);
Output:
Array ( [gruen] => avokado [rot] => apfel [gelb] => banane )
Hope that helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.