A
A
Andrey Kirilchuk2018-05-10 18:29:34
PHP
Andrey Kirilchuk, 2018-05-10 18:29:34

How to select the same value from two multidimensional arrays in php?

There are two multidimensional arrays after JSON parsing and processing

["items"]=> array(2)
    { 
    [0]=> object(stdClass)#2 (4)
      { 
   		["id"]=> int(29) 
   		["from_id"]=> int(-145381893) 
   		["date"]=> int(1525428495) 
   		["text"]=> string(181) "текст1" 
   		}
    [1]=> object(stdClass)#4 (4)
 			{ 
     	["id"]=> int(28) 
     	["from_id"]=> int(72325239) 
     	["date"]=> int(1525428062) 
     	["text"]=> string(276) "текст2"

and
["profiles"]=> array(3)
    { 	 	
   	[0]=> object(stdClass)#28 (3)
   		{
     	["id"]=> int(33367167) 
     	["first_name"]=> string(10) "Иван" 
     	["last_name"]=> string(22) "Иванов" 
     	}
   	[1]=> object(stdClass)#29 (3)
      { 
   	 	["id"]=> int(72325239) 
   		["first_name"]=> string(8) "Петр" 
     	["last_name"]=> string(16) "Петров" 
     	}

   	[2]=> object(stdClass)#30 (3)
   		{ 	
   		["id"]=> int(123060350) 
   		["first_name"]=> string(10) "Сергей" 
   		["last_name"]=> string(16) "Сергеев" 
   		}
   	}

Initially, this is all even in one array. But I don't think it makes much of a difference.
How can you display the names and text of the message in one array, provided that the "from_id" of the first must match the "id" of the second array?
those. from the above example, the output should be something like:
Petr Petrov - Text2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-05-10
@Rsa97

$profiles = array_combine(
              array_map(function($profile) { return $profile->id; }, $data['profiles']), 
              $data['profiles']);
foreach ($data['items'] as $item) {
  echo $profile[$item->from_id]->first_name, ' ', 
       $profile[$item->from_id]->last_name, ' - ', 
       $items->text, "\n";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question