array rebuilding & assignment into another array index key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
oliur
Forum Commoner
Posts: 29
Joined: Tue May 26, 2009 3:43 am

array rebuilding & assignment into another array index key

Post by oliur »

The following code doesn't seem to work. If some of you can point out where I am going wrong I'd much appreciate that.
My guess is I am going all wrong in rebuilding the array. Also, the last bit $data['comment_row'] = $amended_comment;
Can I assign an array into an indexed array like this?

Here is my code.

Code: Select all

 
 
// take a string and look for expressions, replace expression with corresponding emoticons
function addSmiley($des){
  $des = (string)$des;
  $expression = array(":P" => "tongue_smile.gif", ":lol:" => "lol.gif");
  for($i=0;$i<count($expression);$i++){
        foreach($expression as $key=>$value)
        $des = str_replace($key,$value,$des);
  }
  return $des;  
}
 
// this could be either an array or database results set
function getComment(){
    $comments_row[] = array("id" => 0, "user" => "Oliur", "comment" => "This is a comment :P");
    $comments_row[] = array("id" =>1, "user"=>"James","comment" =>"This is another comment :lol:");
    
    return $comments_row;
}
 
$comments = getComment();
 
// replace smiley expression with emoticons
// rebuild the array
for($i=0;$i<count($comments);$i++){
  foreach($comments[$i] as $key){
      if($key == "comment")
        $value = addSmiley($value);
      $amended_comment[] = array($key=>$value);
 }
}
// assign the rebuilt array to another array index so it can be used in Codeigniter. In the following example, $comment_row will now contain the rebuilt array and we can loop through this in our view and display the comments with emoticons. 
 
$data['comment_row'] = $amended_comment;
 
 
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: array rebuilding & assignment into another array index key

Post by Apollo »

Here's the problem:
oliur wrote:foreach($comments[$i] as $key)
This will actually just traverse the values in the $comments array, not its keys.

Try this instead, then it should work:
oliur wrote:foreach($comments[$i] as $key => $value)
Post Reply