Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [JavaScript][PHP][AJAX]Problem z porównywaniem tablic i JSON
Dukov
post 2.12.2017, 12:55:56
Post #1





Grupa: Zarejestrowani
Postów: 69
Pomógł: 0
Dołączył: 21.03.2017

Ostrzeżenie: (0%)
-----


Witam, mam taki kod, problem mam taki, że echo json_encode wykonuje się kilka razy, drugi problem, to nie wiem jak porównać tablice, chodzi o to, żeby w obu tablicach było dokładnie to samo, ni mniej ni więcej. Jak w tablicy a mam ['x','y'] w tablicy b mam ['y','z'] to w wyniku chciałbym mieć ['x','y','z']

  1. <?php
  2. $array = $_POST['list'];
  3. $userID = $_SESSION['log'];
  4. $result = null;
  5. function getData($userID, $array){
  6. function compare($a, $b){
  7.  
  8. if ($a === $b) {
  9. return 0;
  10. }
  11. return ($a > $b)? 1:-1;
  12. }
  13.  
  14. try{
  15.  
  16.  
  17. $stmt = null;
  18. $conn = new PDO("mysql:host=localhost;dbname=list", 'root', '');
  19. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  20. $stmt = $conn->query("SELECT noteText FROM notes WHERE userID='$userID'");
  21. $row = $stmt->fetch();
  22.  
  23. $result = array_diff_uassoc($row, $array, 'compare');
  24.  
  25.  
  26. foreach ($result as $note) {
  27.  
  28.  
  29. $stmt = $conn->prepare("INSERT INTO notes (noteText, userID) VALUES (:note, '$userID')");
  30. $stmt->execute(array(':note' => $note));
  31.  
  32. }
  33. echo json_encode($result);
  34. $conn = null;
  35.  
  36.  
  37. }
  38. catch(PDOException $e)
  39. {
  40. return false;
  41. $e->getMessage();
  42. }
  43. }
  44.  
  45.  
  46.  
  47.  
  48. getData($userID,$array);
  49.  
  50. ?>


A tu kod js
  1. function synchronize(){
  2.  
  3. var listArray = [];
  4. if (typeof li[0] != 'undefined') {
  5.  
  6. for (let i = 0; i< li.length; i++){
  7. listArray[i] = li[i].textContent;
  8.  
  9. }
  10.  
  11. $.post(
  12. "scripts/synchronize.php",
  13. {
  14. list: listArray
  15. },
  16. function(data){
  17.  
  18. let a = Object.keys(data).map(function(key) { return data });
  19. alert(a);
  20. }
  21. );
  22. }
  23. }


Ten post edytował Dukov 2.12.2017, 12:56:33
Go to the top of the page
+Quote Post
trzczy
post 2.12.2017, 13:10:36
Post #2





Grupa: Zarejestrowani
Postów: 460
Pomógł: 49
Dołączył: 5.06.2011

Ostrzeżenie: (0%)
-----


Patrzę na 6. i 7. linię pierwszego kodu. Tam jest definicja funkcji wewnątrz definicji drugiej funkcji? Chyba powinny być definiowane niezależnie.
Go to the top of the page
+Quote Post
Dukov
post 2.12.2017, 14:09:37
Post #3





Grupa: Zarejestrowani
Postów: 69
Pomógł: 0
Dołączył: 21.03.2017

Ostrzeżenie: (0%)
-----


To akurat jest mało istotne dla działania smile.gif
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 16.06.2025 - 23:29