我在 PHP 中有一個包含多個陣列項的關聯陣列,其中一些陣列項具有特定值,例如 ccdbh-743748,而有些則沒有。我需要通過在此陣列上運行回圈來檢查是否有任何陣列項具有此值 ccdbh-743748,然后向該陣列項添加一個新鍵,如“profile_type”=>“primary”。如果另一個陣列項上沒有匹配的值,則像這樣向該陣列項添加一個新鍵。'profile_type' => '次要'
這是陣列結構。
0 => array(
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => '[email protected]'
),
array(
'id' => 'uisvuiacsiodciosd',
'name' => 'test',
'email' => '[email protected]'
),
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => '[email protected]'
)
),
1 => array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => '[email protected]'
),
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => '[email protected]'
)
)
I want the result should be like this
0 => array(
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => '[email protected]'
'profile_type' => 'primary'
),
array(
'id' => 'uisvuiacsiodciosd',
'name' => 'test',
'email' => '[email protected]'
'profile_type' => 'secondary'
),
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => '[email protected]'
'profile_type' => 'secondary'
)
),
1 => array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => '[email protected]'
'profile_type' => 'secondary'
),
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => '[email protected]',
'profile_type' => 'primary'
)
)
此查詢的任何漸進式解決方法,無論是使用預構建的 PHP 函式還是一些自定義解決方案。
uj5u.com熱心網友回復:
可能有更優雅的方法來解決這個問題,但你可以只使用幾個 foreach 回圈......
foreach( $source as $sub ){
$newsub=[];
foreach ($sub as $item) {
$p = ($item['id']==='ccdbh-743748') ? 'primary' : 'secondary';
$item['profile_type']=$p;
$newsub[]=$item;
}
$newsource[]=$newsub;
}
print_r($newsource);
示例:https : //tehplayground.com/s5QTv7QfBde6V8pi
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384854.html
上一篇:如何在androidjava中決議json物件內的陣列?
下一篇:反應:使用多個復選框過濾陣列串列
