开发者

PHP array combine where second value matches condition maintaining order

开发者 https://www.devze.com 2023-03-06 01:47 出处:网络
First Array [0] => Array ( [name] => Car [selected] => 1 ) [1] => Array ( [name] => Boat [selected] => 1

First Array

[0] => Array
    (
        [name] => Car
        [selected] => 1
    )

[1] => Array
    (
        [name] => Boat
        [selected] => 1
    )

[2] => Array
    (
        [name] => Bike

    )

[3] => Array
    (
        [name] => Tank
    )

[4] => Array
    (
        [name] => Aircraft
    )

Second Array:

 [0] => Array
    (
        [name] => Boat
        [code] => PLA


    )

[1] => Array
    (
        [name] => Car
        [code] => GTO


    )

So 开发者_运维知识库what I need is to create new array containing all the values of the first array but the 'selected' entries need to be in the order of the second array.

Desired Array:

[0] => Array
        (
            [name] => Boat
            [selected] => 1
        )

    [1] => Array
        (
            [name] => Car
            [selected] => 1
        )

    [2] => Array
        (
            [name] => Boat

        )

    [3] => Array
        (
            [name] => Tank
        )

    [4] => Array
        (
            [name] => Aircraft
        )


$desiredArray = array();
$checkArray = array();
$arrayToAdd =array();
foreach ($secondArray as $item)
{
    foreach($firstArray as $item2)
    {
        if($item2['name'] == $item['name'] && $item2['selected'])
        {
            $n = count($desiredArray);
            $desiredArray[$n]['name'] = $item['name'];
            $desiredArray[$n]['selected'] = 1;
            $checkArray[] = $item['name'];
        }               
    }
}
foreach($firstArray as $item)
{
    if(!in_array($item['name'], $checkArray))
    {
        $desiredArray[]['name'] = $item['name'];
    }
}

Try this, I can't say i'm proud of it but it might just do what you need. This code assumes that both the First and Second arrays have corresponding name fields. I haven't tested this extensively but please feel free to use it if you need it.


foreach($second as $k => $v) if(isset($v['selected')) $selected[$v['name']] = $v;
foreach($first as $k => $v){
   $Desired[]['name'] = $v['name'];
   if(isset($selected[$v['name']])) $Desired[]['selected'] = 1;
}


So let me just get this straight so i can actually try to answer your question :

Your goal is to make sure the selected items in your " first " array get sorted the same way as your " second " array. So you'd want the same array values, in a different order, and that order is the order specified in the " second " array?

0

精彩评论

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