当前正在使用C进行项目开发,但是我必须生成一个大型结构,由于我对PHP更加熟悉,因此我认为这将在PHP中生成。
我有2个数组。第一个很简单(比这大得多,但我认为这足以复制问题):
$vehicles = [
'vehicleSuper' => [ "adder", "autarch", "banshee2", "bullet" ],
'vehicleSport' => [ "alpha", "banshee", "bestiagts", "blista2" ],
//...
];
第二个数组如下:
$textures = [
'candc_apartments' => [
"limo2_b", "limo2",
],
'candc_default' => [
"marshall_flag18_b", "mesa_b", "rentbus", "marshall_flag21_b", "crusader", "boxville4", "buzzard_b", "dukes2_b", "dukes",
],
'lgm_default' => [
"hotknife", "coquette", "voltic_tless", "vacca", "infernus", "cogcabri_b", "stinger_b", "banshee_b", "ztype", "ninef", "jb700", "superd", "monroe_b", "rapidgt2_b", "khamel", "comet2_b", "cheetah_b", "rapidgt_b", "stinger", "carbon_b", "surano_convertable_b", "rapidgt2", "infernus_b", "jb700_b", "ninef_b", "stingerg", "superd_b", "bullet_b", "ztype_b", "hotknife_b", "cogcabri", "surano_convertable", "rapidgt", "stingerg_b", "coquette_b", "bullet", "carbon", "ninef2", "carboniz", "cheetah", "adder_b", "entityxf", "adder", "feltzer",
],
];
现在我使用上面的2个数组生成这样的列表:
echo '<pre>';
foreach($vehicles as $category => $val) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($val as $item) {
echo " { \"" . $item . "\", \"" . array_search($item, array_column($textures, $item)) . "\", \"\" },\n";
}
echo '}';
echo '<hr>';
}
这将输出类似于:
{ "adder", "", "" },
最后2个值为空。 我要实现的目标:用$textures
数组中的值填充这些值。在这种情况下,我试图像这样填充它:
// arg 1: name from $vehicles
// arg 2: key from $textures
// arg 3: val from $textures
{ "adder", "lgm_default", "adder" },
当前,我的array_search($item, array_column($textures, $item))
方法似乎不起作用。我将如何去工作呢?感谢您的帮助,谢谢大家!
答案 0 :(得分:0)
array_column($textures, $item)
将在名为$textures
的数组$item
键中搜索,但是没有该名称的键,因此返回false,您需要在{{1}上循环}数组并搜索值$textures
是否存在:
$item
答案 1 :(得分:0)
如果要在给定的一对子阵列中查看多个匹配项,array_intersect()
将比较两个子阵列一次并迭代结果。这比对子数组之一的每个元素运行全新的array_search()
调用更为有效。
代码:(Demo)
foreach($vehicles as $category => $v_vals) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($textures as $k => $t_vals) {
foreach (array_intersect($v_vals, $t_vals) as $match) {
echo " { \"$match\", \"$k\", \"$match\" },\n";
}
}
echo "}\n";
}
输出:
vehicleSpawner vehicleSuper[] = {
{ "adder", "lgm_default", "adder" },
{ "bullet", "lgm_default", "bullet" },
}
vehicleSpawner vehicleSport[] = {
}
如果这不是您想要的确切输出格式/结构,可以对其进行调整以适应。