0

我需要组合两种不同的数据类型,一个数组和一个数组对象。

然后我需要按照某个属性(日期)的顺序在页面上显示它们。

访问标记类似于以下内容:

foreach($array as $item){
$item['date'];
}

foreach($object as $item){
$item->post->date
}

array_merge 是我需要的,还是不同的?

并不是说如果可能的话我想即时执行此操作,因为数据将迅速变化并且不需要存储。

谢谢!

4

4 回答 4

1
foreach($array as $item){
 $array_new[] = $item['date'];
 }

 foreach($object as $item){
  $array_new[] = $item->post->date;
 }

 sort($array_new);
于 2012-09-19T15:04:15.787 回答
1

这是我的做法:

// array we will use for sorting
$finalArray = array();
// add the array's using the date as the key
foreach($array as $item){
     $key = $item['date']; // use date here, example $key = date('l \t\h\e jS',$item['date']);
     $finalArray[$key] = $item;
}
// add the objects's using the date as the key
foreach($object as $item){
     $finalArray[$item->post->date] = $item;
}
//now sort by keys as Xeoncross noted
ksort($finalArray);
foreach($finalArray as $date=>$objOrArray){
     if(is_array($objOrArray)){
          //do your array printing here
     } else {
          //do your object printing here
     }
}

Ofcourse we can turn the object into an array with get_object_vars, and use whatever sorting function on the final array, the important part is that we want to sort by date and that's why we need it to be our key.

Hope that helped.

于 2012-09-19T15:15:08.783 回答
0
$dates = array();

foreach ($array as $item) {
  $dates[] = $item['date'];
}


foreach ($object as $item) {
    $dates[] = $item->post->date;
}

sort($dates);

foreach ($dates as $date) {
   echo $date;
}
于 2012-09-19T15:02:58.407 回答
0

如果您需要来自对象的多个值(不仅仅是date)并且您不介意删除重复项,则可以尝试此操作。

// $array is already defined right?
$object = json_decode(json_encode($object), TRUE);
$data = array_merge($array, $object);

print_r($data); // now test it

http://us2.php.net/array_merge
http://us3.php.net/json_decode(注意第二个TRUE参数)

编辑

根据 Perfection 的回答,(并重新阅读问题)我会这样做:

$finalArray = array();
foreach($array as $item)
{
     $finalArray[$item['date']] = $item;
}

foreach($object as $item)
{
     $finalArray[$item->post->date] = json_decode(json_encode($item), TRUE);
}

ksort($finalArray);

foreach($finalArray as $date => $item)
{
    // Everything is an array now
}
于 2012-09-19T15:03:26.400 回答