0

Thats my first post here, so first of all, sorry for mistakes. I Cant solve some problem. I have to create an array from two other arrays :

Array#1:

$a = array(5, 2, 3);

Array#2:

$b = array(0 => array(
                      'key1' => '2',
                      'key2' => 'content2'),
          (1 => array(
                      'key1' => '3',
                      'key2' => 'content3'),
          (2 => array( 
                      'key1' => '5', 
                      'key2' => 'content1');

My output array have to be sth like that:

$output = array(0 => array(
                      'key1' => '5',
                      'key2' => 'content1'),
          (1 => array(
                      'key1' => '2',
                      'key2' => 'content2'),
          (2 => array( 
                      'key1' => '3', 
                      'key2' => 'content3');

And i totally dont know how to solve my problem. No idea what to do. I tried almost everything. Any help? How to start (again)?

2 Answers 2

1

You can achieve this via foreach loops:

$a = array(5, 2, 3);
$b = array(
    array('key1' => '2', 'key2' => 'content2'),
    array('key1' => '3','key2' => 'content3'),
    array('key1' => '5', 'key2' => 'content1')
);

$new = array();
foreach($a as $key) {
    foreach($b as $item) {
        if($item['key1'] == $key) {
            array_push($new, $item);
        }
    }
}

Example


Note

Please attempt the question before posting your code.

What you should be looking at is PHP's array sorting functions and creating a solution to match what you require. Best to look at uasort()/usort()

Sign up to request clarification or add additional context in comments.

Comments

1

try a loop to create the new table

$x = array(5, 2, 3);
$y = array(0 => array(
                      'key1' => '2',
                      'key2' => 'content2'),
          1 => array(
                      'key1' => '3',
                      'key2' => 'content3'),
          2 => array( 
                      'key1' => '5', 
                      'key2' => 'content1'));

$new_arr = array();

foreach ($x as $xvalue) {
foreach ($y as $yvalue) {
   if($yvalue['key1']==$xvalue) {
$new_arr[] = $yvalue;
}
}
}
var_dump($new_arr);

sandbox

http://sandbox.onlinephpfunctions.com/code/7cd210a0282279af9dfe97395ea8eba04d9eb137

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.