Where in (Array of Ids)

MySQL PHP - SELECT WHERE id = array()?

Use IN.

$sql = 'SELECT * 
FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

Find object by id in an array of JavaScript objects

Use the find() method:

myArray.find(x => x.id === '45').foo;

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo);

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

Array of IDs - how to select with JavaScript / JQuery?

Don't you forget "old fashioned" getElementById - it doesn't require hashing the ids. Then just feed nodes to jQuery to get a jQuery object:

var ids = ['jq-primarySearch', 'jq-n-CSS'];
var nodes = $.map( ids, function(i) { return document.getElementById(i) } );
var jqObj = $(nodes);

Mysql where id is in array

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

NB: the syntax is:

SELECT * FROM table WHERE column IN('value1','value2','value3')

Check, whether an array contains an object with id that matches list of ids

I'd suggest you use a Set. Since you are searching your data for specific keys, this will have much better performances on large search arrays:

const data = [  {id: 1, value: false},  {id: 2, value: true},  {id: 3, value: false},  {id: 4, value: true},  {id: 5, value: true}]
const search = (data, terms) => { terms = new Set(terms) return data.filter(({ id }) => terms.has(id))}
console.log(search(data, [1, 5]))


Related Topics



Leave a reply



Submit