我与PHP的工作,并有一个数组的数组,看起来是这样的:如何合并与同类键一个键的值不同的数组的数组元素只
Array(
[0] => Array(
[id] =>1,
[name]=>"edward",
[asset]=>"somesong.mp3"
),
[1] => Array(
[id] =>1,
[name]=>"edward",
[asset]=>"somemovie.mov"
),
[2] => Array(
[id] =>2,
[name]=>"sally",
[asset]=>"anothersong.mp3"
),
[3] => Array(
[id] =>2,
[name]=>"sally",
[asset]=>"anothermovie.mov"
),
...
)
正如你可以看到,他们的主阵列中每个元素之间的相似性,仅与[asset]键的值不同。我想合并主阵列中的元件以便每个[资产]的两个值被保持在新的元件,这样
FinalArray(
[0] => Array(
[id] =>1,
[name]=>"edward",
[song]=>"somesong.mp3",
[movie]=>"somemovie.mov"
),
[1] => Array(
[id] =>2,
[name]=>"sally",
[song]=>"anothersong.mp3",
[movie]=>"anothermovie.mov"
)
...
)
我开始使用内和外foreach()
环的组合使用,探索结构
// $person and $person02 are copies of the same array
foreach($person as $key=>$value){
// grab an element in this loop
$currElement=$person[$key];
foreach($person2 as $key2=>$value2){
$currElement2=$person2[$key2];
// compare $currElement to $currElement2
if($currElement['id']==$currElement2['id']){
// determine if [asset] is an mp3 or mov
$currAsset2=$currElement2['asset'];
$currAsset =$currElement['asset'];
$ext = substr(strrchr($currAsset,'.'),1)
if($ext=='mp3'){
// then we have a song and should store it
$song=$currAsset['asset'];
$movie=$currAsset2['asset'];
}else{
// switch sides if you like
$song=$currAsset2['asset'];
$movie=$currAsset['asset'];
}
}
// create a new array and add it to the result array
$newArrEl = array(
'id' =>$currElement['id'],
'name' =>$currElement['id'],
'song' => $song,
'movie' => $movie
);
$resultArray.push(); // add to final array
}
}
}
事情是,我探索了一堆PHP数组函数的组合,似乎无法得到它很正确。所以我希望这里的某个人也能帮助我解决这个问题。我怎样才能获得原始数据与类似的值合并成新的元素添加到最终数组?
刚刚更新了答案,使其可以运行与提供的样本含量 – 2013-03-07 03:31:39