php iki (veya daha fazla ..) çok boyutlu diziler birleştirmek

1 Cevap php

Ben farklı parametreler ile birkaç kez çalıştırdığınızda bir sorgu var. Ben jQuery sonuçlarını döndürmek için bir xml ayrıştırıcı kullanıyorum.

Ben ilk girdisi yazmadan ilk 'düğüm' üzerindeki sonuçlarını birleştirmek için bir yol bulmak gibi olamaz.

Basitleştirilmiş kod örneği:

$temp1 = returnArray(0);

$temp2 = returnArray(1);

$data = array_merge($temp1, $temp2);

print_r($data);

function returnArray($switch)
{
    if($switch == 0)
    {
        $data['data']['first'] = "something";
    } else {
        $data['data']['second'] = "something ELSE";
    }
    return $data;
}

Array ( [data] => Array ( [second] => something ELSE ) ) dışarı baskı sonuçları - $ ısı2 $ Temp1 üzerine.Yapıyor. Ben bu bana kafa karıştırıcı array_merge varsayılan davranış (), diye anlıyorum.

Ben de $data = $temp1+$temp2; ya da benzeri bir şey yapıyor denedim ...

$data = returnArray(0);

$data += returnArray(1);

baskılar Array ( [data] => Array ( [first] => something ) )

veya ...

$data = returnArray(0);

$data .= returnArray(1);
print_r($data);

baskılar ArrayArray

Ben birlikte bu hack sona erdi:

$data['data'] = returnArray(0);
$data['data'] = returnArray(1);

function returnArray($switch){
  if($switch == 0) return Array('first' => 'something');
  else return Array('second' => 'something else');
}

Hangi ben tüm bu mutlu değilim ... bu durumda yapılan iş alır rağmen daha karmaşık bir durum meydana geldiğinde, bunun gelecekte tüm bu geçerli olmayacaktır.

Is there a better way to take two associative, multi-dimensional arrays and combine them without overwriting?

EDIT:

Ben yöntemi, yeniden genişletilebilir olması ve 2 + boyutları ile 2 + dizileri idare edebilmek istiyorum.

1 Cevap

PHP aslında adında bir fonksiyon sağlar array_merge_recursive() which is used exactly in this type of scenario. From the documentation page:

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Example:

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

Output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)