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?
You’re on the right track. Check for an array. If it’s an array, call it recursively for each item in the array.
In this recursive function, it will parse a single string or an array of strings.