从另一个数组中过滤数组

时间:2016-09-14 14:30:06

标签: php arrays

我有2个阵列

  • $首先,这是我的模型,用于排序我的结果并包含一个 周的天数列表(这是一个例子,它每周都在变化)
  • $ second,这是5周内35天的列表(从星期一到1日 周日5),身份证号码

作为$ result,我得到了一个像$ first一样的数组,但是来自$ second的数据(ID,post_title,post_name)

我可以使用以下方式获得结果:

$posts = array_filter($second, function ($post) use ($first) {
  return in_array($post->post_name, $first);
});

但是问题$ posts并没有像$ first那样订购。

由于

$FIRST
Array
(
    [0] => Monday-5
    [1] => Tuesday-5
    [2] => Wednsday-5
    [3] => Thursday-1
    [4] => Friday-1
    [5] => Saturday-1
    [6] => Sunday-1
)

$SECOND
 Array
(
    [0] => WP_Post Object
        (
            [ID] => 2878
            [post_title] => Monday-1
            [post_name]  => monday-1
        )

    [1] => WP_Post Object
        (
            ID] => 2879
            [post_title] => Tuesday-5
            [post_name]  => tuesday-5
        )
    ...

    [34] => WP_Post Object
        (
            ID] => 2899
            [post_title] => Sunday-5
            [post_name]  => sunday-5
        )
)

1 个答案:

答案 0 :(得分:0)

如果我理解你,你想要一个结果数组首先包含[post_title] => Monday-5的所有元素,那么所有[post_title] => Tuesday-5依此类推,对吧?

然后创建第三个空数组$result。在$first上迭代$second,在$second上迭代,并将$result中的所有项目复制到$first[$i] == $second[$i]['post_title'],以满足您的条件$result = array(); foreach($first as $scope){ foreach($second as $id=>$item){ if($item->post_title == $scope){ $result[$id] = $item; } } }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")
request.returnsObjectsAsFaults = false
do {
    let entityTableInCoreData = try newPrivateQueueContext.fetch(request)
    for i in entityTableInCoreData {
        if let a = i.valueForKey("b") as? String {
            print(a)
        }
    }
} catch {
}