Unset/Delete repeating Elements from Array PHP












0















I have a messages table that stores messages between users.Using the following i show messages based on the users and when users click load more messages are fetch with offset:



        $offset      = $_POST['offset'];
$limit = 10;

$stmt = $db_con->query("SELECT sender,recipient,sending_time,read_time,CASE WHEN LENGTH(content) > 7 THEN CONCAT(substring(content, 1, 49), '...') ELSE content END content,recipient_status FROM messages WHERE (sender='admin' OR recipient='admin') ORDER BY sending_time DESC LIMIT $offset,$limit");
$stmt->execute();
$db_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_posts = ceil($db_count("messages","id","WHERE (sender='admin' OR recipient='admin')","")[0]);
$MSGS_array = array();
$MSGS = '';
$posts = abs($offset-$limit);

foreach($db_messages as $key => $value) {
if($value['sender']=='admin'){$my = $value['recipient']; }else if ($value['recipient']=='admin'){ $my =$value['sender']; }else { $my=$value['sender'];}
$messages = array("user"=>$my,"sending_time"=>$value['sending_time'],"read_time"=>$value['read_time'],"content"=>$value['content'],"recipient_status"=>$value['recipient_status']);
}
foreach ($messages as $message) {
$MSGS_array[$message['user']] = $message;
}
$non_unique_users = array_filter(array_count_values(array_column($messages, 'user')), function ($v) { return $v != 1; });
$duplicates = array_filter($messages, function ($v) use($non_unique_users) { return array_key_exists($v['user'], $non_unique_users); });
//setcookie("username", "John Carter", time()+30*24*60*60);
foreach($MSGS_array as $key => $message){
$MSGS .= '<li><a id="'.$message['user'].'" class="view-headerMSG list-group-item b-rad-0 p10 b0 m0"><div class="online-users pull-left mr5"><img src="../uploads/userprofile/default/avatar.jpg" onerror="this.onerror=null;imgDefault(this);" alt="avatar" class="online-users-img"><span title="online"></span></div><strong class="text-primary h4 mb2">'.$message['user'].'<small class="pull-right">'.$ToReadableTime('@'.$message['sending_time']).'</small></strong><div><small class="text-muted">'.$message['content'].'</small></div></a></li>';
}
echo json_encode(['MSGS' => $MSGS,"posts" => $posts,"total_posts" => $total_posts,"duplicates"=>$MSGS_array]);


WHAT THE CODE DOES?



On page load, ajax request sent to php for fetching messages with the offset 0 and limit 10 .The 1st foreach loop creates an array and the 2nd foreach remove duplicates having key 'user' .



But when i click load more, next 10 messages are fetched (as in the first fetch duplicated messages were removed and i have stored the duplicated/removed keys and values in $duplicates). These messages also contains those messages which were already fetched and appended to the messagebox.



The logic i have in my mind is when fetching first time(i.e offset 0) the $duplicates should be stored in cookie and then after that when the fetch is made with offset greater than 0(such as 10) then the cookie value should be merged with $messages array using array_merge and then the similar values should be unset /deleted and this is the part where i don't know how can i unset ?



OR



is there any way we can compare the cookie value(that is an array of multidimensional) with the $MSGS_array from which the duplicated values have been removed and in the comparison we can do something like unsetting/deleting the key and value that are similar?



Any suggestions ?










share|improve this question





























    0















    I have a messages table that stores messages between users.Using the following i show messages based on the users and when users click load more messages are fetch with offset:



            $offset      = $_POST['offset'];
    $limit = 10;

    $stmt = $db_con->query("SELECT sender,recipient,sending_time,read_time,CASE WHEN LENGTH(content) > 7 THEN CONCAT(substring(content, 1, 49), '...') ELSE content END content,recipient_status FROM messages WHERE (sender='admin' OR recipient='admin') ORDER BY sending_time DESC LIMIT $offset,$limit");
    $stmt->execute();
    $db_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_posts = ceil($db_count("messages","id","WHERE (sender='admin' OR recipient='admin')","")[0]);
    $MSGS_array = array();
    $MSGS = '';
    $posts = abs($offset-$limit);

    foreach($db_messages as $key => $value) {
    if($value['sender']=='admin'){$my = $value['recipient']; }else if ($value['recipient']=='admin'){ $my =$value['sender']; }else { $my=$value['sender'];}
    $messages = array("user"=>$my,"sending_time"=>$value['sending_time'],"read_time"=>$value['read_time'],"content"=>$value['content'],"recipient_status"=>$value['recipient_status']);
    }
    foreach ($messages as $message) {
    $MSGS_array[$message['user']] = $message;
    }
    $non_unique_users = array_filter(array_count_values(array_column($messages, 'user')), function ($v) { return $v != 1; });
    $duplicates = array_filter($messages, function ($v) use($non_unique_users) { return array_key_exists($v['user'], $non_unique_users); });
    //setcookie("username", "John Carter", time()+30*24*60*60);
    foreach($MSGS_array as $key => $message){
    $MSGS .= '<li><a id="'.$message['user'].'" class="view-headerMSG list-group-item b-rad-0 p10 b0 m0"><div class="online-users pull-left mr5"><img src="../uploads/userprofile/default/avatar.jpg" onerror="this.onerror=null;imgDefault(this);" alt="avatar" class="online-users-img"><span title="online"></span></div><strong class="text-primary h4 mb2">'.$message['user'].'<small class="pull-right">'.$ToReadableTime('@'.$message['sending_time']).'</small></strong><div><small class="text-muted">'.$message['content'].'</small></div></a></li>';
    }
    echo json_encode(['MSGS' => $MSGS,"posts" => $posts,"total_posts" => $total_posts,"duplicates"=>$MSGS_array]);


    WHAT THE CODE DOES?



    On page load, ajax request sent to php for fetching messages with the offset 0 and limit 10 .The 1st foreach loop creates an array and the 2nd foreach remove duplicates having key 'user' .



    But when i click load more, next 10 messages are fetched (as in the first fetch duplicated messages were removed and i have stored the duplicated/removed keys and values in $duplicates). These messages also contains those messages which were already fetched and appended to the messagebox.



    The logic i have in my mind is when fetching first time(i.e offset 0) the $duplicates should be stored in cookie and then after that when the fetch is made with offset greater than 0(such as 10) then the cookie value should be merged with $messages array using array_merge and then the similar values should be unset /deleted and this is the part where i don't know how can i unset ?



    OR



    is there any way we can compare the cookie value(that is an array of multidimensional) with the $MSGS_array from which the duplicated values have been removed and in the comparison we can do something like unsetting/deleting the key and value that are similar?



    Any suggestions ?










    share|improve this question



























      0












      0








      0








      I have a messages table that stores messages between users.Using the following i show messages based on the users and when users click load more messages are fetch with offset:



              $offset      = $_POST['offset'];
      $limit = 10;

      $stmt = $db_con->query("SELECT sender,recipient,sending_time,read_time,CASE WHEN LENGTH(content) > 7 THEN CONCAT(substring(content, 1, 49), '...') ELSE content END content,recipient_status FROM messages WHERE (sender='admin' OR recipient='admin') ORDER BY sending_time DESC LIMIT $offset,$limit");
      $stmt->execute();
      $db_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
      $total_posts = ceil($db_count("messages","id","WHERE (sender='admin' OR recipient='admin')","")[0]);
      $MSGS_array = array();
      $MSGS = '';
      $posts = abs($offset-$limit);

      foreach($db_messages as $key => $value) {
      if($value['sender']=='admin'){$my = $value['recipient']; }else if ($value['recipient']=='admin'){ $my =$value['sender']; }else { $my=$value['sender'];}
      $messages = array("user"=>$my,"sending_time"=>$value['sending_time'],"read_time"=>$value['read_time'],"content"=>$value['content'],"recipient_status"=>$value['recipient_status']);
      }
      foreach ($messages as $message) {
      $MSGS_array[$message['user']] = $message;
      }
      $non_unique_users = array_filter(array_count_values(array_column($messages, 'user')), function ($v) { return $v != 1; });
      $duplicates = array_filter($messages, function ($v) use($non_unique_users) { return array_key_exists($v['user'], $non_unique_users); });
      //setcookie("username", "John Carter", time()+30*24*60*60);
      foreach($MSGS_array as $key => $message){
      $MSGS .= '<li><a id="'.$message['user'].'" class="view-headerMSG list-group-item b-rad-0 p10 b0 m0"><div class="online-users pull-left mr5"><img src="../uploads/userprofile/default/avatar.jpg" onerror="this.onerror=null;imgDefault(this);" alt="avatar" class="online-users-img"><span title="online"></span></div><strong class="text-primary h4 mb2">'.$message['user'].'<small class="pull-right">'.$ToReadableTime('@'.$message['sending_time']).'</small></strong><div><small class="text-muted">'.$message['content'].'</small></div></a></li>';
      }
      echo json_encode(['MSGS' => $MSGS,"posts" => $posts,"total_posts" => $total_posts,"duplicates"=>$MSGS_array]);


      WHAT THE CODE DOES?



      On page load, ajax request sent to php for fetching messages with the offset 0 and limit 10 .The 1st foreach loop creates an array and the 2nd foreach remove duplicates having key 'user' .



      But when i click load more, next 10 messages are fetched (as in the first fetch duplicated messages were removed and i have stored the duplicated/removed keys and values in $duplicates). These messages also contains those messages which were already fetched and appended to the messagebox.



      The logic i have in my mind is when fetching first time(i.e offset 0) the $duplicates should be stored in cookie and then after that when the fetch is made with offset greater than 0(such as 10) then the cookie value should be merged with $messages array using array_merge and then the similar values should be unset /deleted and this is the part where i don't know how can i unset ?



      OR



      is there any way we can compare the cookie value(that is an array of multidimensional) with the $MSGS_array from which the duplicated values have been removed and in the comparison we can do something like unsetting/deleting the key and value that are similar?



      Any suggestions ?










      share|improve this question
















      I have a messages table that stores messages between users.Using the following i show messages based on the users and when users click load more messages are fetch with offset:



              $offset      = $_POST['offset'];
      $limit = 10;

      $stmt = $db_con->query("SELECT sender,recipient,sending_time,read_time,CASE WHEN LENGTH(content) > 7 THEN CONCAT(substring(content, 1, 49), '...') ELSE content END content,recipient_status FROM messages WHERE (sender='admin' OR recipient='admin') ORDER BY sending_time DESC LIMIT $offset,$limit");
      $stmt->execute();
      $db_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
      $total_posts = ceil($db_count("messages","id","WHERE (sender='admin' OR recipient='admin')","")[0]);
      $MSGS_array = array();
      $MSGS = '';
      $posts = abs($offset-$limit);

      foreach($db_messages as $key => $value) {
      if($value['sender']=='admin'){$my = $value['recipient']; }else if ($value['recipient']=='admin'){ $my =$value['sender']; }else { $my=$value['sender'];}
      $messages = array("user"=>$my,"sending_time"=>$value['sending_time'],"read_time"=>$value['read_time'],"content"=>$value['content'],"recipient_status"=>$value['recipient_status']);
      }
      foreach ($messages as $message) {
      $MSGS_array[$message['user']] = $message;
      }
      $non_unique_users = array_filter(array_count_values(array_column($messages, 'user')), function ($v) { return $v != 1; });
      $duplicates = array_filter($messages, function ($v) use($non_unique_users) { return array_key_exists($v['user'], $non_unique_users); });
      //setcookie("username", "John Carter", time()+30*24*60*60);
      foreach($MSGS_array as $key => $message){
      $MSGS .= '<li><a id="'.$message['user'].'" class="view-headerMSG list-group-item b-rad-0 p10 b0 m0"><div class="online-users pull-left mr5"><img src="../uploads/userprofile/default/avatar.jpg" onerror="this.onerror=null;imgDefault(this);" alt="avatar" class="online-users-img"><span title="online"></span></div><strong class="text-primary h4 mb2">'.$message['user'].'<small class="pull-right">'.$ToReadableTime('@'.$message['sending_time']).'</small></strong><div><small class="text-muted">'.$message['content'].'</small></div></a></li>';
      }
      echo json_encode(['MSGS' => $MSGS,"posts" => $posts,"total_posts" => $total_posts,"duplicates"=>$MSGS_array]);


      WHAT THE CODE DOES?



      On page load, ajax request sent to php for fetching messages with the offset 0 and limit 10 .The 1st foreach loop creates an array and the 2nd foreach remove duplicates having key 'user' .



      But when i click load more, next 10 messages are fetched (as in the first fetch duplicated messages were removed and i have stored the duplicated/removed keys and values in $duplicates). These messages also contains those messages which were already fetched and appended to the messagebox.



      The logic i have in my mind is when fetching first time(i.e offset 0) the $duplicates should be stored in cookie and then after that when the fetch is made with offset greater than 0(such as 10) then the cookie value should be merged with $messages array using array_merge and then the similar values should be unset /deleted and this is the part where i don't know how can i unset ?



      OR



      is there any way we can compare the cookie value(that is an array of multidimensional) with the $MSGS_array from which the duplicated values have been removed and in the comparison we can do something like unsetting/deleting the key and value that are similar?



      Any suggestions ?







      php mysql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 8:35







      MR_AMDEV

















      asked Nov 25 '18 at 8:29









      MR_AMDEVMR_AMDEV

      16611




      16611
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465830%2funset-delete-repeating-elements-from-array-php%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465830%2funset-delete-repeating-elements-from-array-php%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Create new schema in PostgreSQL using DBeaver

          Deepest pit of an array with Javascript: test on Codility

          Costa Masnaga