开发者

Sorting keys of array values by preserving another array

开发者 https://www.devze.com 2023-02-10 18:31 出处:网络
I need to compare the values of array from another array. Something I did, but I do not know how to preserve keys.

I need to compare the values of array from another array. Something I did, but I do not know how to preserve keys.

$razeni=Array(0=>1,1=>2,2=>0,3=>3);
$myservices=Array(0=>"text0", 1=>"text1", 2=>"text2", 3=>"text3", 4=>"text4", 5=>"text5", 6=>"text6", 7=>"text7");

Now compare

foreach ($razeni as $key=>$value) {
  $myservices_[$value] = $myservices[$value];
  unset($myservices[$value]);    
}

if (isset($myservices_))
{
  $myservices = array_merge($myservices_, $myservices);
}

and result:

Array
(
    [0] => text1
    [1] => text2
    [2] => text0
    [3] => text3
    [4] => text4
    [5] => text5
    [6] => text6
    [开发者_如何学Python7] => text7
)

But I needed this result

Array
(
    [1] => text1
    [2] => text2
    [0] => text0
    [3] => text3
    [4] => text4
    [5] => text5
    [6] => text6
    [7] => text7
)


instead of using array_merge use

$myservices = $myservices_ + $myservices;

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator.

0

精彩评论

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