Jump to content

Array Help


Skewled
Go to solution Solved by denno020,

Recommended Posts

I'm using codeigniter as the framework and I have a mysql return that is being json_encode() so that my jQuery script can work with the data to display it in my view.
 
I'm doing this as a learning exercise and I'm stumped. I want to take the result_array() from the query and manipulate the data, so I would like to have anyone willing to help me, to walk me through the issue so I can learn.
 
Data from MySQL:

blog_id |  content | comment_id | comment_text
-------------------------------------------------
 2        Blog2Text    4           comment4text
 2        Blog2Text    7           comment7text
 2        Blog2Text    8           comment8text
 5        Blog5Text    9           comment9text
 5        Blog5Text    11          comment11text

This works for retrieving the data perfectly and I can credit Psycho for assistance with my query from here: http://forums.phpfreaks.com/topic/287690-need-help-with-joins/

 

So fear each blog as in blog_id / content I want to have the unique comments posted with them. So the data should now be filtered and output:

Blog2Text
comment4text
comment7text
comment8text

Blog5Text
comment8text
comment9text
comment11text

In my mind I'm doing the following pseudo code:

 

1. Create a variable to store the blog_id

2. Set up condition to scan the array for each unique blog_id and add it to a new array along with the comments for that blog_id

3. Return the new array json_encode() from the function

 

Thank You!

Link to comment
Share on other sites

  • Solution

If you want to do it using an array, and provided your mysql results array looks like this

$results = array(
  array(
    "blog_id" => "2",
    "content" => "Blog2Text",
    "comment_id" => "4",
    "comment_text" => "comment4text",
  ),
  array(
    "blog_id" => "2",
    "content" => "Blog2Text",
    "comment_id" => "7",
    "comment_text" => "comment7text",
  ),
  //etc.
)

Then you can create your array like this:

$outputArr = array();
foreach ($results as $result) {
  //Initialise array for the blog ID of the current $result, if it's not already done so
  if (!isset($outputArr[$result['blog_id']])) {
    $outputArr[$result['blog_id']] = array();
  }
  //Append the comment_text for this result to the array for this blog_id
  $outputArr[$result['blog_id']][] = $result['comment_text'];
}
$output = json_encode($outputArr);

Which will result in an output array looking like this:

$outputArr = array(
  2 => array(
    "comment4text",
    "comment7text",
  )
);

Hopefully that helps you out.

Denno

Edited by denno020
Link to comment
Share on other sites

Denno,

 

 Thank you for the reply and I see what you were doing for the most part. I have difficulty when working with data and arrays so I'm practicing.

 

Here is the data returned by my query:

 


Array
(
    [0] => Array
        (
            [blog_id] => 35
            [dateposted] => 2014-04-10
            [content] => <p>Wow this is <span style="color: #008000;"><em><span style="font-size: 14pt;"><strong>very nice...</strong></span></em></span></p>
            [title] => Thanks
            [published] => 1
            [login] => admin
            [img] => public/img/blog-image.png
            [username] => Skewled
            [comment] => thanks
        )


    [1] => Array
        (
            [blog_id] => 35
            [dateposted] => 2014-04-10
            [content] => <p>Wow this is <span style="color: #008000;"><em><span style="font-size: 14pt;"><strong>very nice...</strong></span></em></span></p>
            [title] => Thanks
            [published] => 1
            [login] => admin
            [img] => public/img/blog-image.png
            [username] => Skewled
            [comment] => fasdfa asdf asd fasdfasd [b]test[/b]
        )


    [2] => Array
        (
            [blog_id] => 34
            [dateposted] => 2014-04-09
            [content] => <p><em><strong>sdfasdf asdafsadf</strong> asdfasd </em> asdfasdf <span style="color: #008000;">asdf asdf asdf asdfsa asfasdfaasdf <span style="color: #000000;">asdfasdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">saf asdfasd <strong>fasdfasdf asdfasdf</strong> asdf adsfa asdfasdf asdf asdf asdfasdfa sdf asdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">sadfs dfasdf asdf asdf asdf</span></span></p>
            [title] => Launch Party
            [published] => 1
            [login] => admin
            [img] => public/img/blog-image.png
            [username] => Skewled
            [comment] => <p><em><strong>sdfasdf asdafsadf</strong> asdfasd </em> asdfasdf <span style="color: #008000;">asdf asdf asdf asdfsa asfasdfaasdf <span style="color: #000000;">asdfasdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">saf asdfasd <strong>fasdfasdf asdfasdf</strong> asdf adsfa asdfasdf asdf asdf asdfasdfa sdf asdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">sadfs dfasdf asdf asdf asdf</span></span></p>
        )


    [3] => Array
        (
            [blog_id] => 34
            [dateposted] => 2014-04-09
            [content] => <p><em><strong>sdfasdf asdafsadf</strong> asdfasd </em> asdfasdf <span style="color: #008000;">asdf asdf asdf asdfsa asfasdfaasdf <span style="color: #000000;">asdfasdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">saf asdfasd <strong>fasdfasdf asdfasdf</strong> asdf adsfa asdfasdf asdf asdf asdfasdfa sdf asdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">sadfs dfasdf asdf asdf asdf</span></span></p>
            [title] => Launch Party
            [published] => 1
            [login] => admin
            [img] => public/img/blog-image.png
            [username] => Skewled
            [comment] => <p><em><strong>sdfasdf asdafsadf</strong> asdfasd </em> asdfasdf <span style="color: #008000;">asdf asdf asdf asdfsa asfasdfaasdf <span style="color: #000000;">asdfasdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">saf asdfasd <strong>fasdfasdf asdfasdf</strong> asdf adsfa asdfasdf asdf asdf asdfasdfa sdf asdf</span></span></p>
<p><span style="color: #008000;"><span style="color: #000000;">sadfs dfasdf asdf asdf asdf</span></span></p>
        )
)

As you can see each blog_id is repeated with a comment, so I'm trying to restructure it so each blog_id is only posted once to the array and then the comments are posted into it. Would I need to add another array to this for each comment so the key's would be unique based off the comment_id?

 

I really appreciate your help and your reply was very clear and concise, my questioning and logic are faulting me here lol.

 

Thanks!

 

 

EDIT:

 

I wanted to show you the json_encoded output that I was working with:

 

non-filtered:

https://www.dropbox.com/s/nsq8vas9469uzit/output0.png

 

filtered:

https://www.dropbox.com/s/4a3h8o7649ee1fo/output1.png

 

 

Edited by Skewled
Link to comment
Share on other sites

I think that you want the same basic structure Psycho provided but to create an array of arrays:

while($row = mysql_fetch_assoc($result))
{

$blog_id=$row['blog_id'];
$myArray[$blog_id][]=Array('content'=>$row['content'],'dateposted'=>$row['date_posted']...);
}

Then, cycle through the array like Psycho cycled through the database.

Edited by davidannis
Link to comment
Share on other sites

Let me just say I love this community and I appreciate all of the input I've gotten, I've learned so much from the help I've received here!

 

Here is the plan in my mind:

 

1. Fetch the data from the database

2. Filter the data so that each blog only get's displayed once and all of the comments are looped underneath it.

    - I'm using jQuery for the client view and currently it's setup as a MVC as well, so functions are seperated from the view which calls from a template which is just the     HTML of the view with the variables that I want to display to the client area.

3. Allow additions to the comments by users

   - jQuery post and update the html area for the comments to append the post

 

I'm doing this to learn something new and I've gotten the system going except this issue, so I'm wondering if my setup is incorrect and I should redo the whole thing or I'm going in the right direction and continue learning more. Eventually I would love to paginate the results using jQuery so I can keep all the blog posts, and an Archive.

 

I've gotten the basics of PHP down and I've moved into the OOP side which has certainly been rewarding and I continue to practice and learn. So I am openly embracing all input I receive here that can help solidify the knowledge I've gained. I'm posing the setup I've coded so everyone can see what I'm working with, I think so far I'm pretty happy with what I've come up with so far but please any input is welcomed!! (:

 

So here is a basic example of my overall setup:

 

PHP API Call:

 

    public function get_blog()
    {               
            $query = $this->db->query(
                "SELECT blog.blog_id, blog.dateposted, blog.content, blog.title, blog.published,
                    user.login, user.img,
                    bc.username, bc.comment
                    FROM blog
                    JOIN user
                      ON blog.user_id = user.user_id
                    LEFT JOIN blog_comments bc
                      ON blog.blog_id = bc.blog_id
                    WHERE blog.published = 1
                    ORDER BY blog.blog_id DESC
                    ");
            
               $data = $query->result_array();
               
                $outputArr = array();


                foreach ($data as $result) {
                  //Initialise array for the blog ID of the current $result, if it's not already done so
                  if (!isset($outputArr[$result['blog_id']])) {
                    $outputArr[$result['blog_id']] = array();
                  }
                  //Append the comment_text for this result to the array for this blog_id
                  $outputArr[$result['blog_id']]['blog_id'] = $result['blog_id'];
                  $outputArr[$result['blog_id']]['dateposted'] = $result['comment'];
                  $outputArr[$result['blog_id']]['content'] = $result['content'];
                  $outputArr[$result['blog_id']]['title'] = $result['title'];
                  $outputArr[$result['blog_id']]['published'] = $result['published'];
                  $outputArr[$result['blog_id']]['login'] = $result['login'];
                  $outputArr[$result['blog_id']]['img'] = $result['img'];
                  $outputArr[$result['blog_id']]['username'] = $result['username'];
                  $outputArr[$result['blog_id']]['comment'] = $result['comment'];
                }               
                
                $result = $outputArr;


        if ($result) {
           $this->output->set_output(json_encode($result));
           return false;
        }
    }
 
 

Template for the View:

 this.blog = function(obj) {
        var output = '';
        output += '<div class="blog-post" style="margin: 5px;">';
        output += '<h2 class="blog-post-title">';
        output += obj.title + '</h2>';
        output += '<p class="blog-post-meta">';
        output += '<img src="' + obj.img +'">' + ' ' + obj.dateposted + ' by ' + obj.login + '</p>';
        output += '<p>' + obj.content + '</p>';
        output += '</div>';
        output += '<span class="options">';
        output += '<a class ="blog_update_display" data-id="' + obj.blog_id + '" href="#"><i class="glyphicon glyphicon-pencil"></i></a> Leave Comment ';
        output += '<div class="blog_comment_container" id="blog_comment_container_'+ obj.blog_id +'"></div>';
        output += '<div class="hide" id="blog_comment_' + obj.blog_id + '">' + obj.comment + '</div>';
        output += '</span>';
        output += '<hr>';
        output += '<span><a class="comment_toggle" data-id="'+ obj.blog_id +'" id="blog_title_' + obj.blog_id + '" href="#">View Comments</a></span> ';
        output += '<div class="hide" id="blog_comment_block_' + obj.blog_id + '">';
        output += '<hr>';
        if (obj.username) {
        output += '<h5 class="users">' + obj.username + ' commented:</h5>';
        output += '<p>' + obj.comment + '</p>';
        } else {
            output += '<p>Be the first to comment!</p>';
        }
        output += '</div>';
        output += '<hr>';
        output += '</div>';
        return output;
    };


    // ------------------------------------------------------------------------
    
    this.blog_comment = function(blog_id) {
        var output = '';
        output += '<form method="post" class="blog_comment_form form-horizontal" action="../api/post_comment">';
        output += '<input class="blog_id" type="hidden" name="blog_id" value="' + blog_id + '" />';
        output += '<div class="input-append">';
        output += '<label for="comment">Comment:</label><br>';
        output += '<textarea style="width:100%" rows="10" class="comment" name="comment" id="comment"></textarea>';
        output += '<input tabindex="3" type="submit" class="btn btn-success" value="Post Comment" />';
        output += '<input type="submit" class="btn blog_comment_cancel" value="Cancel" />';        
        output += '</form>';
        return output;
    };

Events:

    var toggle_comments = function() {
      $('body').on("click", ".comment_toggle", function (evt) {
          evt.preventDefault;
          
          var blog_id = $(this).data('id');
          
          $("#blog_comment_block_" + blog_id).toggleClass('hide');
          return false;
      });
    };
    
    // ------------------------------------------------------------------------
    
    var add_comment = function() {
        $("body").on("submit", ".blog_comment_form", function(evt) {
           evt.preventDefault();
           
           var form = $(this);
           var url = $(this).attr('action');
           var postData = {
               blog_id: $(this).find('.blog_id').val(),
               comment: $(this).find('.comment').val()
           };
           
           //console.log(postData);          
           
           $.post(url, postData, function(o) {
               if(o.result == 1) {
                   Result.success("Successfuly Added Comment.");                     
                   $("#blog_comment_" + postData.blog_id).html(postData.comment);
                   form.remove();
               } else {
                   Result.error("No Changes Made.");
              }
           }, 'json');
        });   
    };
    
    
    // ------------------------------------------------------------------------
    
    var update_blog_display = function() {
        $("body").on('click', '.blog_update_display', function(e) {
            // Debug: console.log(e);
            e.preventDefault();                     
            
            var blog_id = $(this).data('id');
            var output = Template.blog_comment(blog_id);


            $("#blog_comment_container_" + blog_id).html(output);
        });
        
        $("body").on("click", ".blog_comment_cancel", function(e) {
            e.preventDefault();       
            $(this).parents('.blog_comment_container').empty();  
        });
    }; 

Loading Code:

 

    var load_blog = function() {
        $.get('api/get_blog', function(o) {
            
            var output = '';
                    
            for (var i = 0; i < o.length; i++) {
                output += Template.blog(o[i]);
            } 
            
            $("#list_blog").html(output);  
        }, 'json');
    };
Link to comment
Share on other sites

You already have the answers given from denno20 and daviddanis. Everything you need to do is to re-structure the array grouping it by blog_id and parse the data by json_encode function.

 

So, instead,

foreach ($data as $result) {
                  //Initialise array for the blog ID of the current $result, if it's not already done so
                  if (!isset($outputArr[$result['blog_id']])) {
                    $outputArr[$result['blog_id']] = array();
                  }
                  //Append the comment_text for this result to the array for this blog_id
                  $outputArr[$result['blog_id']]['blog_id'] = $result['blog_id'];
                  $outputArr[$result['blog_id']]['dateposted'] = $result['comment'];
                  $outputArr[$result['blog_id']]['content'] = $result['content'];
                  $outputArr[$result['blog_id']]['title'] = $result['title'];
                  $outputArr[$result['blog_id']]['published'] = $result['published'];
                  $outputArr[$result['blog_id']]['login'] = $result['login'];
                  $outputArr[$result['blog_id']]['img'] = $result['img'];
                  $outputArr[$result['blog_id']]['username'] = $result['username'];
                  $outputArr[$result['blog_id']]['comment'] = $result['comment'];
                }  

// use

foreach ($data as $row) {
    if (!isset($outputArr[$row['blog_id']])) {
                    $outputArr[$row['blog_id']] = array();
     }
    $outputArr[$row['blog_id']][] = $row;
}

if(!empty($outputArr))
$this->output->set_output(json_encode($outputArr));
             
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.