2014-06-26 64 views
0

我是PHP的新手,樂於學習。 我最近在完成練習時遇到了問題。 Here`s是我必須做的:將數據從數組中移到另一個數組

我需要定義,第一,一個多維數組女巫包含了生產商和某些手機的型號

EG:

$model = array( 
    "manufacurer" => array ("model1", "model2", ...), 
    "manufacurer2" => "array("model3", model4", ...), 

); 

下一個任務:從上面的數組$model開始,我必須生成另一個多維數組,我們稱之爲$shop。 它應該是這樣的:

$shop = array("model1"=>array("manufacurer"=> "manufacurer1", 
           "caractheristics" => array("lenght"=>... 
           "wide"=>..., 
           "weight"=>...) 
      ), 
      "model2"=>array("manufacurer"=>...etc 

這裏是我的代碼:

<?php 

$modele = array( 
      "Nokia" => array ("3310", "n8", "1100"), 
      "Samsung" => array("Galaxy S7", "Bean", "e220"), 
      "Sony" => array("Xperia", "K750", "W810") 
); 
print_r($modele); 
// it has stored my values 
echo "<br>"; 
$magazin = array(
      '$model["Nokia"][0]' => array(
               'manufacturer' => '$modele[2]' 
// How do I use the values from the $model array to $shop array? If i print_r($model["Nokia"][0]) it returnes 3310, witch is ok, but when I print_r($magazin) it returns: Array ([$modele["Nokia"][0]] => Array ([producator] => $modele[2])) 
) 
); 
print_r($magazin); 

?> 

回答

0

從變量省略',如:

​​

的外觀也對這個link

0
$magazin = array(); 
$magazin[$model['Nokia'][0]] = array(
    "manufacurer"=> "manufacurer1", 
    "caractheristics" => array(
    "lenght" => ... 
    "wide" => ..., 
    "weight" => ... 
) 
); 
0

當你引用它總是一個字符串,所以如果你刪除引號,那麼你的代碼已經工作。
下面是一個例子,還增加了代碼來自動化它;

<?php 

$modelsByManufacturer = array(
    "Nokia" => array("3310", "n8", "1100"), 
    "Samsung" => array("Galaxy S7", "Bean", "e220"), 
    "Sony" => array("Xperia", "K750", "W810") 
); 

echo "<hr />"; 
print_r($modelsByManufacturer); 

// if you'd hardcode it it would look like this: 
$magazin = array(
    $modelsByManufacturer["Nokia"][0] => array(
     'manufacturer' => $modelsByManufacturer["Nokia"] 
    ) 
); 

echo "<hr />"; 
print_r($magazin); 

// if you'd automate it it would look like this: 

// create empty array to fill 
$magazin = array(); 

// loop over the data source, use 'as $key => $value' syntax to get both the key and the value (which is the list of models) 
foreach ($modelsByManufacturer as $manufacturer => $models) { 
    // loop over the child array, the models to add them 
    foreach ($models as $model) { 
     $magazin[$model] = array(
      'manufacturer' => $manufacturer, 
      'model'  => $model, 
     ); 
    } 
} 

echo "<hr />"; 
print_r($magazin); 
1

取下單引號

$magazin = array( $model["Nokia"][0] => array( 'manufacturer' => $modele[2] ) );

此外,MODELEassociative array所以你應該使用的關鍵,而不是指數的情況下,你添加/ AT的開頭刪除的東西array:

$magazin = array( $model["Nokia"][0] => array( 'manufacturer' => $modele["Sony"] ) );

。 。另外,我猜測製造商你正在尋找單詞「索尼」,而不是它保存在該鍵的陣列..在這種情況下,你或者只是鍵入「索尼」,或者你在位置2獲得鑰匙

$magazin = array( $model["Nokia"][0] => array( 'manufacturer' => array_keys($modele)[2] ) );

相關問題