Home >Backend Development >PHP Tutorial >javascript - [Algorithm] Set the randomly given key-value pair to the first position in the array. How to implement this?

javascript - [Algorithm] Set the randomly given key-value pair to the first position in the array. How to implement this?

WBOY
WBOYOriginal
2016-09-08 08:43:52876browse

Give me an example:

<code>$arr = array(
    '175' => '金针菇'
    '100' => '银针菇'
);

$arr2 = array(
    '65'  => '白萝卜'
    '67'  => '黑萝卜'
    '84'  => '黄萝卜'
    '100' => '银针菇'
    '90'  => '大萝卜'
    '175' => '金针菇'
);
</code>

The final effect is like this:

<code>$arr3 = array(
    '175' => '金针菇'
    '100' => '银针菇'
    '65'  => '白萝卜'
    '67'  => '黑萝卜'
    '84'  => '黄萝卜'
    '90'  => '大萝卜'
    
);</code>

Please tell me, how to implement such an algorithm?

Reply content:

Give me an example:

<code>$arr = array(
    '175' => '金针菇'
    '100' => '银针菇'
);

$arr2 = array(
    '65'  => '白萝卜'
    '67'  => '黑萝卜'
    '84'  => '黄萝卜'
    '100' => '银针菇'
    '90'  => '大萝卜'
    '175' => '金针菇'
);
</code>

The final effect is like this:

<code>$arr3 = array(
    '175' => '金针菇'
    '100' => '银针菇'
    '65'  => '白萝卜'
    '67'  => '黑萝卜'
    '84'  => '黄萝卜'
    '90'  => '大萝卜'
    
);</code>

Please tell me how to implement such an algorithm?

This question has been closed. I wrote it myself. When I asked the question, I thought it was complicated. After I calmed down, I realized how simple it is. I’ll post the code:

<code>foreach ($arr2 as $key => $value) {
    if(!in_array($value, $arr)) {
        $arr[$key] = $value;
    }
}
var_dump($arr);</code>

<code>return($arr + $arr2);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn