M
M
Mikha Pankratov2015-04-01 05:16:06
Yii
Mikha Pankratov, 2015-04-01 05:16:06

How to compare 2 dissimilar objects or array Yii2?

Good night, a bit late) and I can’t figure out how to do this. So I got two user and friends objects
using hasMany . I need to find out which id intersect with the first object and assign a new array element to show that these guys are already friends. But at the same time, I need all the elements of the array with which I compare in order to display them. If you need to, I can var_dump these two objects, is it necessary? Tell me how best to do it? Maybe better in a view?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Frank, 2015-04-01
@Akellacom

I could not understand anything from your question, but I think the array_diff function php.net/manual/en/function.array-diff.php should help
you

M
Mikha Pankratov, 2015-04-01
@frmax

See I have two objects.
For example, objects (I will choose arrays):

array(3) { 
[0]=> array(1) { 
[0]=> array(2) { 
        ["id"]=> string(1) "2" 
        ["username"]=> string(4) "ivan" } } 
[1]=> array(1) { [0]=> array(2) { 
       ["id"]=> string(1) "3" 
      ["username"]=> string(8) "Саша" } } 
[2]=> array(1) { [0]=> array(2) { 
        ["id"]=> string(2) "19" 
        ["username"]=> string(8) "Макс" } } }

array(2) { 
[0]=> array(1) { [0]=> array(2) { 
          ["id"]=> string(1) "1" 
          ["username"]=> string(5) "maxim" } } 
[1]=> array(1) { [0]=> array(2) { 
          ["id"]=> string(2) "19" 
          ["username"]=> string(8) "Макс" } } }

As you can see, this id 19 / [0]=> array(2) { ["id"]=> string(2) "19" ["username"]=> string(8) "Max" } } intersects
T. e. as a result we get 3 array
array(2) { [0]=> array(1) { [0]=> array(2) { 
          ["id"]=> string(1) "1" 
          ["username"]=> string(5) "maxim" } } 
[1]=> array(1) { [0]=> array(2) { <b>
         ["id"]=> string(2) "19" 
         ["username"]=> string(8) "Макс", 
         ['friend']=>1</b>} } }

L
LAV45, 2015-04-01
@LAV45

$users = User::find()
    ->indexBy('id')
    ->all();

$friends = Friend::find()
    ->indexBy('id')
    ->all();

$result = array_intersect_key($users, $friends);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question