我是PHP新手,愿意学习。 我最近在完成练习时遇到了一个问题。 这就是我要做的事情:
首先,我需要定义一个包含生产者和某些手机型号的多维数组
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 :(得分:1)
删除单引号
$magazin = array(
$model["Nokia"][0] => array(
'manufacturer' => $modele[2]
)
);
另外, modele 是associative array所以你应该使用键而不是索引,以防你在数组的开头添加/删除东西:
$magazin = array(
$model["Nokia"][0] => array(
'manufacturer' => $modele["Sony"]
)
);
..我也猜测制造商你正在寻找“索尼”这个词,而不是它在那把钥匙上的数字......在这种情况下,你要么输入“索尼”,要么你得到关键位置2
$magazin = array(
$model["Nokia"][0] => array(
'manufacturer' => array_keys($modele)[2]
)
);
答案 1 :(得分:0)
答案 2 :(得分:0)
$magazin = array();
$magazin[$model['Nokia'][0]] = array(
"manufacurer"=> "manufacurer1",
"caractheristics" => array(
"lenght" => ...
"wide" => ...,
"weight" => ...
)
);
答案 3 :(得分: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);