1

I am trying to compare a JSON return with set ARRAY.

The JSON is showing OK, this is set as $a. The ARRAY is coded and is showing OK, this is set as $b.

I'd like the output to be a percentage, not including duplicates.

THIS IS NOW EDITED.

<?php
$loggedUser =  auth()->user()->id ; // returns authenticated user id.
$pdo = new PDO('mysql:host=****;dbname=****', '****', '****');

$stmt = $pdo->prepare('SELECT movie_id FROM user_watch_lists WHERE user_id = :user');
$stmt->execute(array('user' => $loggedUser));
$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC);

$a = $result_array;
$b = array(297761);

print_r($a);
print_r($b);

$c = 0;
foreach ($a as $k=>$v) {
    if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;
?>

Contents of the return above (echo $a; and $echo b; and echo ($c/count($a))*100;):

Array ( [0] => Array ( [movie_id] => 297761 ) ) 
Array ( [0] => 297761 ) 
0

This should return 100%. I can see why, but unsure how to fix. I've tried to change the loop to go in to the array but get ERROR.

foreach ($a as $r=>$k=>$v) {
    if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;
nathan
  • 67
  • 6
  • 4
    you're open to SQL injection and should address immediately :) – treyBake Jul 08 '19 at 08:01
  • Hi treyBake, how do I do this? – nathan Jul 08 '19 at 08:05
  • 1
    https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php <- this should help :) – treyBake Jul 08 '19 at 08:06
  • 2
    use parameters when you do a SQL query – Giacomo M Jul 08 '19 at 08:06
  • EDITED: I've not, I believe, corrected the SQL injection issue. I think the problem is now that one array has a KEY and the other doesn't? – nathan Jul 08 '19 at 08:30
  • 1
    Can you show contents of arrays? – Justinas Jul 08 '19 at 08:32
  • 1
    1) `$a` is a list of rows, so if you want to compare with `$b` I think you need to compare `$b` against `$a[0]` - the first row only. (even though you only returned one row, `fetchAll()` can _potentially_ fetch more than that, and so always returns the result in an array.) 2) `FETCH_ASSOC` returns an associative array with keys according to the column names. If you want a simple array with numeric indexes then use `FETCH_NUM` instead – ADyson Jul 08 '19 at 09:36

0 Answers0