开发者

Can't get a specific array structure

开发者 https://www.devze.com 2023-04-12 20:22 出处:网络
I\'m hanging around since hours to get a specific Array and can\'t figure it out. I get this start Array with a foreach loop :

I'm hanging around since hours to get a specific Array and can't figure it out.

I get this start Array with a foreach loop :

Array
(
   [0] => Title 1
   [1] => Image 1.jpg
   [2] => Title 2
   [3] => Image 2.png
   [4] => Text 1
)

And I have an Array generated to order the 1st Array (when the user drag and drop e开发者_如何学Clements of the 1st array)

Array
(
   [0] => 1
   [1] => 4
   [2] => 0
   [3] => 2
   [4] => 3
)

What I need is to link the VALUES of the 2nd array (1, 4, 0, 2, 3) with the keys of the first Array ([0],1 ...) to get exactly that :

Array
(
   [1] => Text 1
   [4] => Image 2.png
   [0] => Image 1.jpg
   [2] => Title 1
   [3] => Title 2
)

I've tried array_combine but it don't gives me the result above.

I've made a schema to understand the problem:

Can't get a specific array structure


Here is some pseudo-code (I copy pasted and was too lazy to correct it to be valid PHP I corrected it):

<?php
$items = Array
(
   0 => 'Title 1',
   1 => 'Image 1.jpg',
   2 => 'Title 2',
   3 => 'Image 2.png',
   4 => 'Text 1',
);
$order = Array
(
   0 => 1,
   1 => 4,
   2 => 0,
   3 => 2,
   4 => 3,
);

foreach ($order as $itemPosition) {
    $sorted[] = $items[ $itemPosition ];
}

// optionally 
ksort($sorted);
var_dump($sorted);

Of course this is assuming your $order array has the keys in order. If it doesn't you may want to do a ksort on it too before you do the foreach.

http://codepad.org/Lq8iw29w


You are taking each value of the second array and use it as key for the second array to obtain the key for the first array while using the second's array order and key the output:

$mapped = array();

foreach($arr2 as $value)
{
    $mapped[$value] = $arr1[$arr2[$value]];
}

Output:

Array
(
    [1] => Text 1
    [4] => Image 2.png
    [0] => Image 1.jpg
    [2] => Title 1
    [3] => Title 2
)

Demo

0

精彩评论

暂无评论...
验证码 换一张
取 消