【发布时间】:2022-01-20 16:55:17
【问题描述】:
我在 PHP 中有一个包含多个数组项的关联数组,其中一些数组项具有特定值,例如 ccdbh-743748,而有些则没有。 我需要通过在该数组上运行一个循环来检查是否有任何数组项具有此值 ccdbh-743748,然后向该数组项添加一个新键,例如“profile_type”=>“primary”。 如果另一个数组项上没有匹配的值,则像这样向该数组项添加一个新键。 'profile_type' => '次要'
这是数组结构。
0 => array(
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com'
),
array(
'id' => 'uisvuiacsiodciosd',
'name' => 'test',
'email' => 'testemail@test.com'
),
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com'
)
),
1 => array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com'
),
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com'
)
)
I want the result should be like this
0 => array(
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com'
'profile_type' => 'primary'
),
array(
'id' => 'uisvuiacsiodciosd',
'name' => 'test',
'email' => 'testemail@test.com'
'profile_type' => 'secondary'
),
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com'
'profile_type' => 'secondary'
)
),
1 => array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com'
'profile_type' => 'secondary'
),
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com',
'profile_type' => 'primary'
)
)
此查询的任何渐进式解决方法,无论是使用预建的 PHP 函数还是对此的一些自定义解决方案。
【问题讨论】:
-
似乎相当直接。到目前为止,您尝试过什么?
-
@Kinglish 我是代码新手,我试图通过使用 array_column 然后 preg_match 值来实现结果,但没有找到如何设置辅助值。
标签: php arrays associative-array