logo
down
shadow

Array PHP, Check if exist multiple elements to another array


Array PHP, Check if exist multiple elements to another array

Content Index :

Array PHP, Check if exist multiple elements to another array
Tag : php , By : user149634
Date : November 27 2020, 09:01 AM

hop of those help? If I understand correctly, you want to indicate for each entry in the static array whether its ID exists in the user array.
You can use array_column to generate an array of all IDs in the user array. Then use in_array to check if each static ID exists in that array. Set a value to 1 if its found and 0 if its not found.
<?php

$static=array(
    array('point'=>50,'title'=>'TITLE 1','id'=>54632),
    array('point'=>50,'title'=>'TITLE 2','id'=>54344),
    array('point'=>50,'title'=>'TITLE 3','id'=>34225),
    array('point'=>50,'title'=>'TITLE 4','id'=>2323245),
    array('point'=>50,'title'=>'TITLE 5','id'=>23872445),
);
$user=array(
    array('id'=>2323245,'title'=>'TITLE 1','point'=>50),
    array('id'=>54344,'title'=>'TITLE 2','point'=>50),
    array('id'=>34225,'title'=>'TITLE 3','point'=>50)
);

$final=array();

foreach ($static as $entry) {
    $final[]=array(
        'found'=>in_array($entry['id'],array_column($user,'id'))?1:0,
        'id'=>$entry['id'],
        'title'=>$entry['title'],
        'point'=>$entry['point']
    );
}

echo"<pre>".print_r($final,true)."</pre>";
Array
(
    [0] => Array
        (
            [found] => 0
            [id] => 54632
            [title] => TITLE 1
            [point] => 50
        )

    [1] => Array
        (
            [found] => 1
            [id] => 54344
            [title] => TITLE 2
            [point] => 50
        )

    [2] => Array
        (
            [found] => 1
            [id] => 34225
            [title] => TITLE 3
            [point] => 50
        )

    [3] => Array
        (
            [found] => 1
            [id] => 2323245
            [title] => TITLE 4
            [point] => 50
        )

    [4] => Array
        (
            [found] => 0
            [id] => 23872445
            [title] => TITLE 5
            [point] => 50
        )

)
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
// initialize the "static" and "user" arrays

$static=array (
  0 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement2',
    'title' => 'Achievement 2',
    'id' => 644081262362202
  ),
  1 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement3',
    'title' => 'Achievement 3',
    'id' => 912599152147444
  ),
  2 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement5',
    'title' => 'Achievement 5',
    'id' => 913757345379232
  ),
  3 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement6',
    'title' => 'Achievement 6',
    'id' => 921989084564878
  ),
  4 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement1',
    'title' => 'Achievement 1',
    'id' => 968802826528055
  ),
  5 => array(
    'data' => array(
      'points' => 50
    ),
    'description' => 'you unlock the achievement4',
    'title' => 'Achievement 4',
    'id' => 1149671038394021
  )
);

$user=array(
  0=>array(
    'data' => array(
      'importance' => 0,
      'achievement' => array (
        'id' => 644081262362202,
        'title' => 'Achievement 2',
        'type' => 'game.achievement',
        'url' => 'http://www.***.com/achievements/achievement2.html'
      )
    ),
    'id' => 104693166566570
  ),
  1 => array (
    'data' => array (
      'importance' => 0,
      'achievement' => array (
        'id' => 968802826528055,
        'title' => 'Achievement 1',
        'type' => 'game.achievement',
        'url' => 'http://www.***.com/achievements/achievement1.html'
      )
    ),
    'id' => 104023386633548
  )
);

// build array of user achievement IDs
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');

// generate final array, with "found" values
$final=array();

foreach ($static as $entry) {
    $final[]=array(
        'found'=>in_array($entry['id'],$user_achvmts)?1:0,
        'id'=>$entry['id'],
        'title'=>$entry['title'],
        'description'=>$entry['description'],
        'points'=>$entry['data']['points']
    );
}

echo"<pre>".print_r($final,true)."</pre>";
Array
(
    [0] => Array
        (
            [found] => 1
            [id] => 644081262362202
            [title] => Achievement 2
            [description] => you unlock the achievement2
            [points] => 50
        )

    [1] => Array
        (
            [found] => 0
            [id] => 912599152147444
            [title] => Achievement 3
            [description] => you unlock the achievement3
            [points] => 50
        )

    [2] => Array
        (
            [found] => 0
            [id] => 913757345379232
            [title] => Achievement 5
            [description] => you unlock the achievement5
            [points] => 50
        )

    [3] => Array
        (
            [found] => 0
            [id] => 921989084564878
            [title] => Achievement 6
            [description] => you unlock the achievement6
            [points] => 50
        )

    [4] => Array
        (
            [found] => 1
            [id] => 968802826528055
            [title] => Achievement 1
            [description] => you unlock the achievement1
            [points] => 50
        )

    [5] => Array
        (
            [found] => 0
            [id] => 1149671038394021
            [title] => Achievement 4
            [description] => you unlock the achievement4
            [points] => 50
        )

)
$user_achvmts = array_map( function($v) {return $v['data']['achievement']['id'];}, $user);
$user_achvmts=[];
foreach ($user as $v) { $user_achvmts[]=$v['data']['achievement']['id']; }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to check if array elements exist in a string


Tag : php , By : Bjørn Lyngwa
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Regarding to your additional comment you could explode your string into single words using explode() or preg_split() and then check this array against the needles-array using array_intersect(). So all the work is done only once.
<?php
$haystack = "Hello Houston, we have a problem";
$haystacks = preg_split("/\b/", $haystack);
$needles = array("Chicago", "New York", "Houston");
$intersect = array_intersect($haystacks, $needles);
$count = count($intersect);

var_dump($count, $intersect);

how to check if elements from a database exist in a array listview android


Tag : android , By : cnemelka
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further your instance a new object.... add your created object in your else like this:
            Model s= new Model(cursor.getString(1),cursor.getString(2));


            if (list.contains(s)) //THIS DOES NOT WORK
            {
                contain=true;
            }
            else 
            {
                list.add(s);
            }

Check if all elements of one array exist in other


Tag : php , By : Kaveh
Date : March 29 2020, 07:55 AM
may help you . First way:
$result = $a === array_intersect($a, $b);
$result = !count(array_diff($a, $b));

Check if all elements of a subarray of an array doesn't exist in the rest of the array


Tag : arrays , By : Mighty Mac
Date : March 29 2020, 07:55 AM
should help you out
Preprocessing: Loop over the array and create a hashmap counts of each element to the count of how often it appears in the array.
array[n] // the input array

Map<int -> int> counts
for i = 1 to n
   counts[array[i]]++
Map<int -> int> queryCounts
for x = i to j
   queryCounts[array[x]]++
for each key y in queryCounts
   if queryCounts[y] != counts[y]
      return "no"
return "yes"
2 -> 2
3 -> 1
4 -> 2
5 -> 1
2 -> 1
5 -> 1
array[n] // the input array

Map<(int, int) -> String> queryResults
for i = 1 to n
   Map<int -> int> queryCounts // clear on every i iteration
   countsWrong = 0
   for j = i to n
      if queryCounts[array[j]] == counts[array[j]]
         countsWrong++ // the counts match, the below operation will make it not match
      queryCounts[array[j]]++
      if queryCounts[array[j]] == counts[array[j]]
         countsWrong--
      if countsWrong == 0
         queryResults[i,j] = "yes"
      else
         queryResults[i,j] = "no"
return queryResults[i,j]
2 -> 1
4 -> 2
4 -> 1
countsWrong = 1 // since 4's count is wrong (not 2)
queryResults[1,1] = "no"
4 -> 2
countsWrong = 0 // 4's count is now right
queryResults[1,2] = "yes"
4 -> 2
2 -> 1
countsWrong = 1 // 2's count is right
queryResults[1,3] = "yes"
4 -> 1
countsWrong = 1 // 4's count is wrong (not 2)
queryResults[2,2] = "no"
4 -> 1
2 -> 1
countsWrong = 1 // 2's count is right, 4's is wrong (not 2)
queryResults[2,3] = "no"
2 -> 1
countsWrong = 0 // 2's count is right
queryResults[1,2] = "yes"

How to check if elements in one array exist in another array if so print the count using Python


Tag : python , By : Tim
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have two arrays , pythonic way:
>>> import collections
>>> a= [1,2,3,4,6,5,5,5,8,9,7,7,7]
>>> b = [1,5,7]
>>> counter = collections.Counter(a)
>>> {x:counter[x] for x in b}
{1: 1, 5: 3, 7: 3}
>>>
Related Posts Related QUESTIONS :
  • Http post request to php with dart
  • How to add a route in with blade into parameters of a component
  • How can i get the source of a 777 - CHMOD php file?
  • Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon"
  • How can I hide a $_GET variable to be more secured in PHP?
  • Login to Gmail Inbox using Curl?
  • Upload Excel or CSV file to MySQL with PHP
  • Outlook Marking Email as Junk Email
  • Upload an image using class.upload.php via AJAX, display image in form using jQuery
  • mysql_connect() causes page to not display (WAMP)
  • How to limit a users uploaded image size using PHP
  • What's the difference whether or not to run PHP in safe mode?
  • Logging in to a website cURL
  • Using php to create a password system with chinese characters
  • PHP is not called properly in IE using set interval function in Javascript
  • How to read pdf, ppt, xl, doc files content into a string in php/python
  • php script for currency conversion
  • In PHP... best way to turn string representation of a folder structure into nested array
  • PayPal for Indian Rupees (INR) any solution
  • PHP Deployment to Live Server
  • Ideal Multi-Developer Lamp Stack?
  • How can I save an image from a file input field using PHP & MySQL?
  • Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in
  • Connecting to external MySQL DB from a web server not running MySQL
  • Is it possible to add custom fields to a Drupal taxonomy term?
  • PHP 6.0 - Roadmap?
  • jQuery wait for ajax call to be over before continuing
  • checkUnique function?
  • How to define an n-m relation in doctrine?
  • Sort the unsorted text file and rewrite to same text file in sorted order
  • Version control a content management system?
  • How can i run Single PHP File using apache-tomcat-6.0.18?
  • Array of objects is empty when I come to retrieve one from the array
  • PHP Library: Calculate a bounding box for a given lat/lng location
  • Good Wordpress Theme/plugin for showing off code examples and scripts
  • Replace all spaces and special symbols with dash in URL using PHP language
  • globally get any field value in user table of logged in user
  • Can you get a job if you know XHTML, CSS and Basic PHP?
  • HTML Upload Form will only upload files found in the directory of the PHP file
  • Determine if a PHP array uses keys or indices
  • Are frameworks really necessary for beginners/intermediates?
  • PHP File Downloading Questions
  • Who owns a php exec tar extracted file?
  • Best way to get timezone of user based on area code
  • Mysql BETWEEN clause being ignored. No syntax error
  • Zend Framework: Getting request object in bootstrap
  • PHP + GD: imagetruecolortopalette not keeping transparency
  • Good Guide For Web App Security?
  • Creating a new wordpress post from twitter tweets
  • Query to show images with recent posts in Wordpress sidebar/widget
  • select & print multiple value from dropdown list
  • Storing a digital signature for bookings on a web based system
  • How to generate all permutations of a string in PHP?
  • How do I get the PostgreSQL PHP extension working on Windows?
  • Parsing WordPress XML, slash:comments syntax?
  • Hide order status in the status dropdown on WooCommerce admin orders page
  • PHP Converting Hex string to Byte Array - converting VB.Net to PHP
  • Mutiple forms using same php mailer script
  • PHP replace string with value from array
  • Laravel group by issues with an inline select statement
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com