Puddinq.com sharing knowledge

Complex array merge

Complex array merge

    /**
     * insert every postId in $featured in the position set in $featuredPost[position] in the cachedIds array
     * - and remove double occurrences
     * - and only in the given time period
     */
    public function insertFeaturedPosts($cachedIds, $featured) {
        foreach ($featured as $featuredPost) {
            unset($cachedIds[$featuredPost['featured_post'][0]]);
            $dateNow = new \DateTime(date('Y-m-d'));

            $dateStart = new \DateTime($featuredPost['starting_date']);
            $dateExpire = new \DateTime($featuredPost['expiration_date']);

            if ($dateStart <= $dateNow && $dateNow <= $dateExpire) {
                $pos = $featuredPost['position'][0] - 1;
                $postId = $featuredPost['featured_post'][0];
                $cachedIds = array_merge(array_slice($cachedIds, 0, $pos), [$postId], array_slice($cachedIds, $pos, NULL));
            }
        }
        return $cachedIds;
    }