簡體   English   中英

如何組合這兩個PHP數組?

[英]How to combine these two PHP arrays?

我在php中有兩個數組,它們是圖像管理系統的一部分。

weighted_images多維數組。 每個子數組都是一個關聯數組,其鍵為'weight'(用於排序)和'id'(圖像的id)。

array(
    156 => array('weight'=>1, 'id'=>156),
    784 => array('weight'=>-2, 'id'=>784),
)

images該數組是用戶輸入。 這是一組圖像ID。

array(784, 346, 748)

我想將它們組合成一個由圖像權重排序的單個數組。 如果圖像沒有重量附加到末尾。

這不是一個特別難的問題,但是我的解決方案遠非優雅,並且無法想象必須有更好的方法來做到這一點。

$t_images = array();
foreach ($weighted_images as $wi) {
  if ( in_array($wi['id'], $images) ) {
    $t_images[$wi['weight']] = $wi['id'];
  }
}
foreach ($images as $image) {
  if ( !$weighted_images[$image] ) {
    $t_images[] = $image;
  }
}
$images = $t_images;

問題:有更好的方法嗎?

Schmalls幾乎是對的,只是錯過了最后一步 -

如果圖像沒有重量附加到末尾。

這是完整的過程。

$array = array_intersect_key($weighted_images, array_fill_keys($images, null));

uasort($array, function($a, $b) {
    if($a['weight'] == $b['weight']) return 0;
    return ($a['weight'] > $b['weight']) ? 1 : -1;
});

$array += array_diff_key($images, $weighted_images);
<?php
$weights = array(
    156 => array('weight'=>1, 'id'=>156),
    784 => array('weight'=>-2, 'id'=>784),
);

$selected = array(784, 346, 748);

$selectedWeights = array();
foreach ($selected as $id)
{
    $weight = 0;
    if (isset($weights[$id]))
    {
        $weight = $weights[$id]['weight'];
    }
    $selectedWeights[$id] = $weight;
}
asort($selectedWeights);

print_r($selectedWeights);
?>

如果我理解你:

$data = array(
156 => array('weight'=>1, 'id'=>156),
784 => array('weight'=>-2, 'id'=>784),
);
$ids = array(156, 784, 431);


function compare_weight($item1, $item2) {
    return $item1['weight'] > $item2['weight'] ? 1 : -1;
}

uashort($data, 'compare_weight');

foreach($ids as $id)
    $data += array($id => array('weight'=>null, 'id'=>$id) );

您可以很容易地得到數組的交集:

$selected_images = array_intersect_key($weighted_images, array_fill_keys($images, null))

array_fill_keys函數使用$images數組作為鍵,使用null作為每個鍵的值。 由於我們使用鍵( array_intersect_key )與數組相交,因此除了第一個數組之外,任何數組的值都無關緊要。

然后你可以使用回調函數按重量排序,如Skirmantas建議:

function cmp_weight($a, $b)
{
    if ($a['weight'] == $b['weight']) {
        return 0;
    }

    return (($a['weight'] > $b['weight']) ? 1 : -1;
}

$images = uasort($selected_images, 'cmp_weight');

如果您使用的是PHP 5.3,則可以使用匿名函數:

$images = uasort($selected_images, function($a, $b)
{
    if ($a['weight'] == $b['weight']) {
        return 0;
    }

    return (($a['weight'] > $b['weight']) ? 1 : -1;
})

我會開始重新考慮$ weighted_images數組。 像這樣的東西,其中鍵是ID,值是重量,可能就足夠了:

$weighted_images = array(
  156 => 1,
  784 => -2,
);
$images = array(156, 784, 431);

然后只做一些排序,並確保你擁有陣列中的所有圖像。

// Images (with weight) ordered
asort($weighted_images);

// Check all images and add at the end the ones with no weight, with null value
foreach ($images as $id) {
  if (!array_key_exists($id, $weighted_images)) {
    $weighted_images[$id] = null;
  }
}

而已。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM