Home > OS >  Compare values using strpos - PHP
Compare values using strpos - PHP

Time:01-05

I am trying to return the user_id if value matches with any comma separated value, I am using strpos but I don't why is it not working with 3rd case:

To Compare: (This value is stored in $myArray variable)

Array
(
    [0] => cloud
    [1] => ai
    [2] => test
)

Compare with: (This value is stored in $array_meta_values variable)

Array
(
    [0] => Array
        (
            [tags] => cloud,ai
            [user_id] => 1
        )

    [1] => Array
        (
            [tags] => cloud,ai,test
            [user_id] => 108
        )

    [2] => Array
        (
            [tags] => storage,backup,ai
            [user_id] => 101
        )

)



function searchForId($meta_value, $array)
{

    foreach ($array as $key => $val) {
        if (strpos($val['tags'], $meta_value)) {
            return $val['user_id'];
        }
    }
}

foreach ($myArray as $usertags) {
        $userids[] = searchForId($usertags, $array_meta_values);
    }
print_r($userids);

Getting this Output:

Array
(
    [1] => 1
    [2] => 108
)

It was supposed to add 101 as third element in output array but don't know why it is not working.

Any help appreciated.

CodePudding user response:

Hi so I tried to replicate you question,

$existing = ['cloud', 'ai', 'test'];

$checker = [

array(
    "tags" => "cloud,ai",
    "user_id" => 1
),

array(
    "tags" => "cloud,ai,test",
    "user_id" => 108
),

array(
    "tags" => "storage,backup,ai",
    "user_id" => 101
)

];

function searchForId($meta_value, $array)
{
$ret_array = [];
foreach ($array as $val) {
    $et = explode(",", $val['tags']);
    if (in_array($meta_value, $et)) {
        $ret_array[] = $val['user_id'];
    }
}

return $ret_array;
}

foreach ($existing as $usertags) {
$userids[$usertags][] = searchForId($usertags, $checker);
}

echo "<pre>";
print_r($userids);

Is this what you looking for?

CodePudding user response:

Your question is quite unclear, but I'll try with this one:

<?php

$myArray = array('cloud', 'ai', 'test');
$array_meta_values = array(
    array(
        'tags' => 'cloud,ai',
        'user_id' => 1,
    ),
    array(
        'tags' => 'cloud,ai,test',
        'user_id' => 108,
    ),
    array(
        'tags' => 'storage,backup,ai',
        'user_id' => 101,
    ),
);

$userids = [];

foreach ($myArray as $value) {
    foreach ($array_meta_values as $array) {
        $arrayValues = explode(',', $array['tags']);
        if (in_array($value, $arrayValues)) {
            $userids[$value][] = $array['user_id'];
        }
    }
}

echo '<pre>';
print_r($userids);

Output:

Array
(
    [cloud] => Array
        (
            [0] => 1
            [1] => 108
        )

    [ai] => Array
        (
            [0] => 1
            [1] => 108
            [2] => 101
        )

    [test] => Array
        (
            [0] => 108
        )

)
  •  Tags:  
  • php
  • Related