2016-03-18 21 views
1

私は2つの配列を持っています。連想配列の各行のキーになるには最初の値から値が必要です。私は正しくそれを述べたと思います。私はこのように見えるように第2のアレイのそれぞれの値を置き換えるために最初の配列から値を必要とするPHP 1つの連想配列キーを別の配列値に置き換える方法

Array 
(
    [field_name0] => first_name 
    [field_name1] => mobile 
    [field_name2] => email 
    [field_name3] => last_name 
) 

Array 
(
[1] => Array 
    (
     [First Name] => Peter 
     [mobile] => 1234567890 
     [email] => [email protected] 
     [Last Name] => Griffin 
    ) 

[2] => Array 
    (
     [First Name] => Al 
     [mobile] => 9874561230 
     [email] => [email protected] 
     [Last Name] => Bundy 
    ) 

) 

Array 
(
[1] => Array 
    (
     [first_name] => Peter 
     [mobile] => 1234567890 
     [email] => [email protected] 
     [last_name] => Griffin 
    ) 

[2] => Array 
    (
     [first_name] => Al 
     [mobile] => 9874561230 
     [email] => [email protected] 
     [last_name] => Bundy 
    ) 

) 

私は、2つの配列を持っています私はこれを達成するためにいくつかの悪い試みをいくつか試してみましたが、それは少し難解です。助けてください。私はこれを行う簡単な方法を見過ごしたと思っています。私が試した何

: -

foreach($field_map as $origKey => $value){ 
     foreach($csvdata as $csvrow){ 
      foreach($csvrow as $cKey => $cValue){ 
        $newKey = $value; 
        $newArray[$newKey] = $cValue; 
      } 
     } 
} 
+0

これは私の知る限り得ているようあきれるほどではない: 'foreachの($ origKey => $値として$ field_map){ foreachの($ csvrow as $ csvrow){ foreach($ csvrow as $ cKey => $ cValue){ $ newKey = $ value; $ newArray [$ newKey] = $ cValue; } } } ' – khtims75

+0

$ field_mapが最初の配列で、$ csvdataが2番目になります – khtims75

+0

khtims75最新の回答を確認してください。 –

答えて

2

このスクリプト:

$users = [ 
    [ 
     'First Name' => 'Peter', 
     'mobile' => 1234567890, 
     'email' => '[email protected]', 
     'Last Name' => 'Griffin', 
    ], 
    [ 
     'First Name' => 'Al', 
     'mobile' => 9874561230, 
     'email' => '[email protected]', 
     'Last Name' => 'Bundy', 
    ], 
]; 

$fields = [ 
    'field_name0' => 'first_name', 
    'field_name1' => 'mobile', 
    'field_name2' => 'email', 
    'field_name3' => 'last_name', 
]; 

$fieldNames = array_values($fields); 
foreach ($users as &$user) { 
    $user = array_combine($fields, array_values($user)); 
} 
print_r($users); 

は、あなたが何を望むか提供します。

効果的には、キーを破棄し、それらのアイテムのシーケンスに依存します。ここで

+0

はい!それでおしまい!まさに私が必要としたもの。ありがとう、コンスタンチン! – khtims75

+0

あなたの条件が私に尋ねたものを適用しても、それはうまくいかないでしょう。 –

+0

ああ?私は自分のコードでいくつかの例をテストし、それがうまくいくかどうかを見ていきます。 – khtims75

関連する問題