1

I want to compare two arrays, one coming from a shoppingcart 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

2
  • There's ambiguity in your example if column 0 in your CSV relates to the quantity field or the ID. Commented Apr 12, 2010 at 13:53
  • mhm, in the csv there is no field for quantity, it's only the id wich shows up in both arrays. As i have mapped the keys properly now (namely "id") this should be no problem anymore, or am i wrong? Commented Apr 12, 2010 at 14:03

3 Answers 3

2

Something like this?

while (($result = fgetcsv($file)) !== false) {
    $checkitems[] = array(
        'id' => $result[0],
        'name' => $result[1],
        'price' => $result[2]
    );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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..

Comments

0

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

Comments

Your Answer

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.