我有2个数组。一个是美国国家的缩写和ids,另一个是国家缩写和其他数据,如下:
数组1:
Array
(
[1] => AL
[2] => AK
[3] => AZ
[4] => CA
[5] => FL
[6] => MA
[7] => IL
)
数组2:
Array
(
[0] => Array
(
[0] => AK
[1] => Other State Data
)
[1] => Array
(
[0] => FL
[1] => Other State Data
)
[2] => Array
(
[0] => AK
[1] => Other State Data
)
[3] => Array
(
[0] => CA
[1] => Other State Data
)
[4] => Array
(
[0] => CA
[1] => Other State Data
)
[5] => Array
(
[0] => FL
[1] => Other State Data
)
[6] => Array
(
[0] => AL
[1] => Other State Data
)
[7] => Array
(
[0] => IL
[1] => Other State Data
)
[8] => Array
(
[0] => AL
[1] => Other State Data
)
[9] => Array
(
[0] => AZ
[1] => Other State Data
)
[10] => Array
(
[0] => MA
[1] => Other State Data
)
)
我试图最后通过比较2个数组并插入第二个数组,第一个数组的关键位置,当有缩写匹配时。所以最终的结果应该是:
Array
(
[0] => Array
(
[0] => AK
[1] => Other State Data
[2] => 2
)
[1] => Array
(
[0] => FL
[1] => Other State Data
[2] => 5
)
... and so on...
我应该考虑使用哪种方便的功能吗?如果不是,一个有效的范例将如何?循环数组并检查每个成员?
*请原谅我没有使用数组值的引号,对不起我的英语,如果那些听起来很糟糕的话。 谢谢!
答案 0 :(得分:2)
首先翻转键/缩写/ ids数组的值,然后使用array_walk
修改主数据数组:
$flipped = array_flip( $abbreviationsArray );
array_walk( $data, function( &$item ) use( $flipped ) {
if( isset( $flipped[ $item[0] ] ) ) $item[] = $flipped[ $item[0] ];
});
array_walk
处理每个数据数组元素:对于每个元素 - 如果在翻转数组中有一个元素与当前元素[0]具有相同的键 - 我们将其添加为元素[2]。
最后$data
看起来像这样:
Array
(
[0] => Array
(
[0] => AK
[1] => Other State Data
[2] => 2
)
[1] => Array
(
[0] => FL
[1] => Other State Data
[2] => 5
)
[2] => Array
(
[0] => AK
[1] => Other State Data
[2] => 2
(...)
)
的 eval.in demo 强>
答案 1 :(得分:1)
根本没有尝试过,但从理论上说它应该可行。循环遍历第二个数组,因为那是您要修改的数组,并在第一个数组中搜索状态代码。如果找到,请将其密钥添加到第二个阵列:
foreach ($secondArray as &$values) {
list ($state, $otherData) = $values;
$stateKey = array_search($state, $firstArray);
if (false !== $stateKey) {
$values[] = $stateKey;
}
}