2013-09-16 61 views
-1

在我的項目上一直工作了幾天,而且我很想在這個項目中做的事情是比較用戶常規做的csv文件在Excel中,每天晚上自動執行。 我從CSV的介紹數組中獲得了信息,但我無法將它們組合起來以獲取每本書的正確信息,因此下面的例子和問題。在php中比較數組並將值從一個賦值到另一個

我有一個CSV文件如下因素陣列(數組1):

Array 
(
[0] => Array 
    (
     [0] => book1 
     [1] => description1 
     [2] => category1 
     [3] => code1 
     [4] => editor1 
     [5] => 0 
     [6] => eur 
     [7] => out of stoc 
    ) 

[1] => Array 
    (
     [0] => book2 
     [1] => description2 
     [2] => category2 
     [3] => code2 
     [4] => editor2 
     [5] => 0 
     [6] => curr2 
     [7] => out of stoc 
    ) 

[2] => Array 
    (
     [0] => book3 
     [1] => description3 
     [2] => category3 
     [3] => code3 
     [4] => editor3 
     [5] => 0 
     [6] => curr3 
     [7] => out of stoc 
    ) 

[3] => 
) 

,並從第二CSV文件的另一個數組(數組2):

Array 
(
[0] => Array 
    (
     [0] => book1 
     [1] => description_from_array2 
     [2] => category_from_array2 
     [3] => code_from_array2 
     [4] => editor_from_array2 
     [5] => 12 
     [6] => eur 
     [7] => in stoc 
    ) 

[1] => Array 
    (
     [0] => book2 
     [1] => description_from_array2 
     [2] => category_from_array2 
     [3] => code_from_array2 
     [4] => editor_from_array2 
     [5] => 13 
     [6] => eur 
     [7] => in stoc 
    ) 

[2] => Array 
    (
     [0] => book4 
     [1] => description_from_array2 
     [2] => category_from_array2 
     [3] => code_from_array2 
     [4] => editor_from_array2 
     [5] => 14 
     [6] => usd 
     [7] => in stoc 
    ) 

[3] => Array 
    (
     [0] => book5 
     [1] => description_from_array2 
     [2] => category_from_array2 
     [3] => code_from_array2 
     [4] => editor_from_array2 
     [5] => 16 
     [6] => usd 
     [7] => in stoc 
    ) 

) 

我想知道如何從array2中找到array1的書籍,獲取數組的形式array2 intro array1。 例如:

Array 
(
[0] => Array 
(
    [0] => book1 
    [1] => description2_from_array2 
    [2] => category2_from_array2 
    [3] => code2_from_array2 
    [4] => editor2_from_array2 
    [5] => 12 
    [6] => eur 
    [7] => in stoc 
) 

[1] => Array 
(
    [0] => book2 
    [1] => description_from_array2 
    [2] => category_from_array2 
    [3] => code_from_array2 
    [4] => editor_from_array2 
    [5] => 13 
    [6] => curr_from_array2 
    [7] => in stoc 
) 

[2] => Array 
(
    [0] => book3 
    [1] => description3 
    [2] => category3 
    [3] => code3 
    [4] => editor3 
    [5] => 0 
    [6] => curr3 
    [7] => out of stoc //because book3 is not found in array2 
) 

[3] => 
) 

對這個問題的任何幫助,將不勝感激,相信的我!

回答

1
//Add keys to array 2 to aid lookup 
$array2Tmp = array(); 
foreach($array2 as $item){ 
    $array2Tmp[$item[0]] = $item; 
} 

$array3 = array(); 
foreach($array1 as $item){ 
    //Use item from second array if it exists 
    if(array_key_exists($item[0],$array2Tmp)){ 
     $array3[] = $array2Tmp[$item[0]]; 
    }else{ 
     $array3[] = $item; 
    } 
} 
+0

非常感謝你,作品像一個魅力 – Rasvan

+0

@Rasvan沒問題,很高興我可以幫助。 – Jim

+0

我可以問你另一個問題嗎? – Rasvan

相關問題