define keys in multidimensional array from csv
I want to compare two arrays, one coming from a sh开发者_开发问答oppingcart and the other one parsed from a csv-file. The array from the shopping cart looks like this:
Array
(
[0] => Array
(
[id] => 7
[qty] => 1
[price] => 07.39
[name] => walkthebridge
[subtotal] => 7.39
)
[1] => Array
(
[id] => 2
[qty] => 1
[price] => 07.39
[name] => milkyway
[subtotal] => 7.39
)
)
The array from my csv-file however looks like this
Array
(
[0] => Array
(
[0] => 1
[1] => walkthebridge
[2] => 07.39
)
[1] => Array
(
[0] => 2
[1] => milkyway
[2] => 07.39
)
)
and is build using this code
$checkitems = array();
$file = fopen('checkitems.csv', 'r');
while (($result = fgetcsv($file)) !== false) {
$checkitems[] = $result;
}
fclose($file);
how can i get the keys in the second array to match those in the first one? ( So that 0 would be id, and 1 would be name and so on)
thanks in advance
Something like this?
while (($result = fgetcsv($file)) !== false) {
$checkitems[] = array(
'id' => $result[0],
'name' => $result[1],
'price' => $result[2]
);
}
Lets say $oldArray is your second 'csv' array, then:
$newArray=array();
foreach($oldArray as $v){
$t=array();
$t['id']=$v[0];
$t['name']=$v[1];
// etc...
$newArray[]=$t;
}
Not tested, but that's one way of mapping the key values..
csv isn't an associative key value storage method. if you want to do that you will need to do it by your self.
at any event you can use array_combine
精彩评论