亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

移動或移動 php 數組鍵

移動或移動 php 數組鍵

PHP
呼啦一陣風 2023-06-30 16:09:58
不太確定如何正確表達這一點,但我正在尋找一些幫助來移動/移動數組鍵,以便頂級數組不包含另一個只有一個項目的數組?;旧鲜沁@樣的:[0] => Array    (        [0] => Array            (                [_id] => 3                [title] => Award winning wedding venue                [subtitle] => Creating a website to reflect the prestige of the brand            )    )[1] => Array    (        [0] => Array            (                [_id] => 5                [title] => Bringing storytelling to life                [subtitle] => Bringing storytelling to life            )    )像這樣:[0] => Array    (        [_id] => 3        [title] => Award winning wedding venue        [subtitle] => Creating a website to reflect the prestige of the brand    )[1] => Array    (        [_id] => 5        [title] => Bringing storytelling to life        [subtitle] => Bringing storytelling to life    )幾乎只是將數組鍵向上移動一位。原始數組是使用以下命令創建的:// Start with manual relation otherwise default to next/prev        foreach ($item['related'] as $id) {            $related[] = perch_collection('Projects', [        'filter' => [          [            'filter' => '_id',            'match'  => 'eq',            'value'  => $id,          ],            // Item is enabled          [            'filter' => 'status',            'match' => 'eq',            'value' => 'enabled',          ],        ],        'skip-template' => true,      ], true);    }
查看完整描述

2 回答

?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

最好修改數組的創建而不是事后更改它。


// Start with manual relation otherwise default to next/prev? ??

foreach ($item['related'] as $id) {

??

? ? $related[] = perch_collection('Projects', [

? ? ? ? 'filter' => [

? ? ? ? ? ? [

? ? ? ? ? ? ? ? 'filter' => '_id',

? ? ? ? ? ? ? ? 'match'? => 'eq',

? ? ? ? ? ? ? ? 'value'? => $id,

? ? ? ? ? ? ],

? ? ? ? ? ? // Item is enabled

? ? ? ? ? ? [

? ? ? ? ? ? ? ? 'filter' => 'status',

? ? ? ? ? ? ? ? 'match' => 'eq',

? ? ? ? ? ? ? ? 'value' => 'enabled',

? ? ? ? ? ? ],

? ? ? ? ],

? ? ? ? 'skip-template' => true,

? ], true)[0];

}

請注意函數調用[0]末尾的perch_collection()。這基本上與我答案的第二部分相同,只是發生得更早。


話雖如此,如果在創建原始數組后仍想更改它,則可以使用一個簡單的 foreach 循環并引用原始數組。


foreach($array as &$arr) {

? ? $arr = $arr[0];

}

&前面使用的$arrreference.?這意味著循環將更改原始數組,因此可以防止臨時數組的開銷。


micmackusa讓我知道另一個使用 的解決方案array_column(),它完全避免了循環。

$array?=?array_column($array,?0);


查看完整回答
反對 回復 2023-06-30
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

解決這個問題的最好辦法就是從源頭入手。這看起來像是從數據庫接收的數據集,因此您也可以嘗試以正確的格式生成它,而不是在收到它后嘗試操作該數組。大多數 DAL 都有方法來操作結果集的返回類型。


但是,如果這是不可能的,并且您始終只有一個嵌套元素,則此循環應該可以解決問題。


for($i = 0; $i <= count($array); $i++) {

    $shifted[$i] = $array[$i][0];

}


查看完整回答
反對 回復 2023-06-30
  • 2 回答
  • 0 關注
  • 165 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號