我试图在PHP中循环一个数组并提取一些值。我在获取以下数组的值时遇到困难:(702,car,707,car2,704car3...)
这就是我的数组的样子:
[data:protected] => Array (
[0] => Array (
[0] => 702
[1] => car
)
[1] => Array (
[0] => 707
[1] => car2
)
[2] => Array (
[0] => 704
[1] => car3
)
[3] => Array (
[0] => 705
[1] => car4
)
[4] => Array (
[0] => 708
[1] => car5
)
[5] => Array (
[0] => 709
[1] => car6
)
[6] => Array (
[0] => 706
[1] => car7
)
[7] => Array (
[0] => 703
[1] => car8
)
)
我试过这个:
foreach($result as $resultItem){
$resultArray[] = $resultItem['n'];
}
print_r($resultArray);
但这只给了我一些价值观:
Array ( [0] => 702 [1] => 707 [2] => 704 [3] => 705 [4] => 708 [5] => 709 [6] => 706 [7] => 703 )
如何访问其他值?
答案 0 :(得分:5)
foreach($result as $resultItem) {
foreach ($resultItem as $resultItemItem) {
$resultArray[] = $resultItemItem;
}
}
如果我看到你的阵列,这应该会很刺激。
答案 1 :(得分:4)
假设数组的维度始终为2,您可以这样做
foreach($result as $resultItem)
{
if(is_array($resultItem))
{
foreach($resultItem as $resultSubItem)
{
$resultArray[] = $resultSubItem;
}
}
else $resultArray[] = $resultItem:
}
如果数组的维度未知且您只想展平数组,请参阅此问题How to Flatten a Multidimensional Array?
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($result));
foreach($it as $v)
{
$resultArray[] = $v;
}
答案 2 :(得分:1)
试试这个
foreach($result as $resultItem){
$resultArray[] = $resultItem[0];
$resultArray[] = $resultItem[1];
}
print_r($resultArray);
答案 3 :(得分:0)
foreach($result as $resultItem){
$resultArray[] = array(
$resultItem[0],
$resultItem[1]
);
}
print_r($resultArray);
你也可以这样做
foreach($result as $resultItem){
$resultArray[$resultItem[0]] = $resultItem[1];
}
print_r($resultArray);
这样你的数组就像
数组([701] =>' car',[702] =>' car',[703] =>' car')
答案 4 :(得分:0)
试试这段代码:
foreach($result as $resultItem){
$resultArray = array_merge($resultArray,$resultItem);
}