Reputation: 1061
So I need to get the part of the array that is holding a specific id, so that I can use the other variables within it.
Here is my current code to create the array:
<?php foreach ($list_subjects as $subject): ?>
subjects.push({
id: parseInt(<?php echo $subject['subject_id']; ?>),
subject_name: "<?php echo $subject['subject_name']; ?>",
course_type: "<?php echo $subject['course_type']; ?>",
num_videos: parseInt(<?php echo $subject['num_videos']; ?>),
subject_tag: "<?php echo $subject['subject_tags']; ?>"
});
<?php endforeach; ?>
(I know mixing PHP in this fashion isn't good practise, but bear with me for this question)
This is the code I'm using to at least try and check if the value is in the array, but it is returning -1 every time, and the value of course_id IS in the array.
alert($.inArray(course_id, subjects.id));
Why is this happening?
Upvotes: 1
Views: 3797
Reputation: 2048
This is a variant of Secators function, except it works without jQuery.
function inArrayById(array, value) {
for(var i = 0; i < array.length; i++) {
if(array[i]["id"] === value) return true;
}
return false;
}
Upvotes: 0
Reputation: 31633
The $.inArray(course_id, subjects.id)
part won't work, as id
is a key of an object inside the subjects
array (thus not a property of subjects
). Try like that:
function inArrayById(array, value)
$.each(array, function(i, element) {
if(element.id === value){
return true;
}
});
return false;
}
alert( inArrayById(subjects, course_id) )
Upvotes: 1