簡體   English   中英

按順序放置數組變量

[英]Put array variables in order

這是我的數組:

    [a] => apple
    [b] => banana
    [c] => Array
    (
        [2] => x
        [4] => y
        [6] => z
    )

我正在尋找一種方法將我的[c]數組變量放在“順序”中。 制作我的數組,看起來像這樣:

    [a] => apple
    [b] => banana
    [c] => Array
(
        [1] => x
        [2] => y
        [3] => z
)

有沒有辦法在沒有自己創建新功能的情況下做到這一點?

試試重新分配c值:

$data['c'] = array_values($data['c']);

它將重新索引您的c數組,但索引將從0開始。 如果你真的想從0開始,試試:

$data['c'] = array_combine(range(1, count($data['c'])), array_values($data['c']))

幸運的是,PHP提供了許多用於數組排序的函數,您不必再編寫另一個函數。

嘗試sort($a['c']) (假設你的數組存儲在$ a變量中)。

$a = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => array(
        '1' => 'x',
        '2' => 'y',
        '3' => 'z',
    ),
);

sort($a['c']);
print_r($a);

輸出:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

如果你不需要對$a['c']的內容進行排序而只想重新索引它(讓它有從0開始的數字連續鍵),那么array_values()就是它所需要的:

$a['c'] = array_values($a['c']);

如果您不知道需要對多少個數組進行排序,請嘗試以下方法:

$testarr = ['a' => 'apple', 'b' => 'banana', 'c' => ['x', 'y', 'z']];

foreach ($testarr as $key => $item) {
    if (is_array($item)) { $arr[$key] = array_values($item); }
    // if (is_array($item)) { $arr[$key] = asort($item); } // use asort() if you want to keep subarray keys
}

暫無
暫無

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

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