通过嵌套的PHP数组进行操作和循环

时间:2010-07-05 01:15:23

标签: php arrays

好的......我讨厌数组......我不理解他们,也不喜欢和他们一起工作......但是我正在开展一个项目,我无法控制我正在拉动的数据,但需要一种方法来排序它变成了我可以操作的格式......

因此,数据看起来像这样:

$arr = Array ( 
[1] => Array ( [December] => a date here [December (2)] => a location here... [December (3)] => an event here... )
[2] => Array ( [December] => a date here [December (2)] => a location here... [December (3)] => an event here... )
[3] => Array ( [December] => a date here [December (2)] => a location here... [December (3)] => an event here... )
[4] => Array ( [December] => a date here [December (2)] => a location here... [December (3)] => an event here... )
[5] => Array ( [December] => a date here [December (2)] => a location here... [December (3)] => an event here... )
)

首先,我需要改变'十二月','十二月(2)'和& '十二月(3)'到'日期','位置'和& '事件' ...

然后我需要一种方法来引用foreach循环或类似的每个数组中的新键,然后我可以插入到数据库中?

类似的东西:

$arr[1][Date];

但我猜$ arr [1]需要像$ arr [$ i] ......?

有人可以帮帮我吗?非常感谢...我试图在某个时候做到这一点......

4 个答案:

答案 0 :(得分:2)

您可能希望将值复制到新数组中。你可以这样做:

foreach ($arr as $a)
{
    // this gets the keys 'December', 'December (2)', etc
    $keys = array_keys($a)

    // this copies the values to the new array
    $newarr['date'] = $a[$keys[0]];
    $newarr['location'] = $a[$keys[1]];
    $newarr['event'] = $a[$keys[2]];
    // ... continue with as many fields as you have or need
}

然后可以通过$newarr[1]['date']访问每个元素,依此类推。在“十二月(3)”等中使用array_keys()代替硬编码的结果是这个函数无论月份都会起作用(我假设您可能必须在1月,2月,等等。

但是,老实说,如果你对阵列感到不舒服,你可能不应该尝试做数据库工作......

答案 1 :(得分:1)

  

首先,我需要改变'十二月','十二月(2)'和& '十二月(3)'到'日期','位置'和& '事件' ...

foreach ($arr as &$a) {
    $a["Date"] = $a["December (2)"];
    unset($a["December (2)"]);
    $a["Location & Event"] = $a["December (3)"];
    unset($a["December (3)"]);
}
//$a is a reference; this avoids accidental overwrites on the last subarray
unset($a);

你可以再次循环数组,你将拥有新的密钥:

foreach ($arr as $a) {
    //do sth with $a["December"];
    //do sth with $a["Date"];
    //do sth with $a["Location & Event"];
}

答案 2 :(得分:0)

这样的事情:

<?php
$array = array(
    array(
        'date' => ...,
        'location' => ...,
        'event' => ....
    ),
    ...
 );
 ?>

答案 3 :(得分:0)

假设密钥总是'12月','12月(2)'等,这应该照顾重命名:

foreach ($array as &$entry) {
    $entry = array('Date' => $entry['December'], 'Location' => $entry['December (2)'], 'Event' => $entry['December (3)']);
}

从那里开始,每个条目都可以在$array[0]['Date']$array[1]['Date']等处访问。您可以在for循环中循环使用$array[$i]['Date'],或者使用其他foreach {1}}循环。这是我将留给你的基本练习。