doubing3662 2012-02-26 02:58
浏览 33
已采纳

在CakePHP中的方法中从模型发送单个对象

I'm basically formatting urls before sending my object to the view to loop through (with a foreach() on $submissions. The problem I'm having is that parse_url() takes a single index and not an entire array object.

I've got this method in my SubmissionsController:

public function newest() {        
    $submissions = $this->Submission->find('all', array(
        'conditions' => array('Submission.approved' => '1'),
        'order' => 'Submission.created DESC'
            ));

    $this->set('submissions', $submissions);
    $this->set('sourceShortUrl', AppController::shortSource($submissions));
}

In my AppController I've got this method which returns the formatted url:

protected function shortSource($source) {
    return $sourceShortUrl = str_ireplace('www.', '', parse_url($source, PHP_URL_HOST));
}

This works for single entries, but parse_url can't take arrays, so is there a way in the controller to send the index of the object? E.g. $submissions['Submission']['source'] before I loop through it in the view?

My alternative was to do something like this in my shortSource($source) method:

if (is_array($source)) {
    for ($i = 0; $i < count($source); $i++) {
        return $sourceShortUrl = str_ireplace('www.', '', parse_url($source[$i]['Submission']['source'], PHP_URL_HOST));
    }
}

But that's just returning the first (obviously). What is the best way to do this?

  • 写回答

1条回答 默认 最新

  • duanqiongdu9916 2012-02-26 03:32
    关注

    You're on the right track. Check for an array. If it's an array, call it recursively for each item in the array.

    /**
    * shortSource
    *
    * Returns an array of URLs with the www. removed from the front of the domain name.
    * 
    * @param mixed $source Either a string or array
    * @return mixed $sourceShortUrl An array of URLs or a single string
    */
    protected function shortSource($source) {
        if (is_array($source)) {
            foreach ($source as $url) {
                $sourceShortUrl[] = $this->shortSource($url);
            }
        } else {
            $sourceShortUrl = str_ireplace('www.', '', parse_url($source, PHP_URL_HOST));
        }
        return $sourceShortUrl;
    }
    

    In this recursive function, it will parse a single string or an array of strings.

    // in the view
    if (is_array($sourceShortUrl)) {
        foreach ($sourceShortUrl as $url) {
            // view specific code for URL here
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应