gpt4 book ai didi

php - 如何比较内部数组键和值并在 PHP 中相应地设置变量的值?

转载 作者:搜寻专家 更新时间:2023-10-31 21:32:17 24 4
gpt4 key购买 nike

我有一个名为 $UserProfile 的大数组,如下所示:

Array
(
[cf_classification] => Array
(
[field_id] => 10
[field_name] => classification
[customValue] => 11
[cg_user_group_id] => 0
[options] => Array
(
[11] => Array
(
[value] => Freshman
)

[12] => Array
(
[value] => Shopomore
)

[13] => Array
(
[value] => Junior
)

[14] => Array
(
[value] => Senior
)

[15] => Array
(
[value] => Masters
)

[16] => Array
(
[value] => Ph.D
)

)

)
)

现在如果你从上面的数组中看到有一个键值对如下:

[customValue] => 11

在上面的数组中还有一个名为options的内层数组如下:

[options] => Array
(
[11] => Array
(
[value] => Freshman
)

[12] => Array
(
[value] => Shopomore
)

[13] => Array
(
[value] => Junior
)

[14] => Array
(
[value] => Senior
)

[15] => Array
(
[value] => Masters
)

[16] => Array
(
[value] => Ph.D
)

)

我想要实现的是将 inner array 选项的键值与 outer array 的键 [customValue] 的值进行比较找到匹配后,将值分配给新变量 $education

简而言之,在上面的例子中 $education 应该有值 'Freshman' 因为 11 是匹配的键和值。所以所需的输出将是

$educaion = 'Freshman';

我的问题是如何通过进行最少数量的比较以编程方式做到这一点?

谢谢。

最佳答案

这可以给你一些想法

我使用了 array_keys_exists($key, $array) 方法检查此键是否存在于数组中

你也可以看看这个 http://php.net/manual/en/ref.array.php

<?php


$user_profile = array(
'cf_classification' => array(
'field_id' => 10,
'field_name' => 'classification',
'customValue' => 11,
'cg_user_group_id' => 0,
'options' => array(
11 => array(
'value' => 'Freshman'
),

12 => array(
'value' => 'Shopomore'
),

13 => array(
'value' => 'Junior'
),

14 => array(
'value' => 'Senior'
),

15 => array(
'value' => 'Masters'
),

16 => array(
'value' => 'Ph.D'
)

)

)
);


$custom_field = $user_profile['cf_classification']['customValue'];
$education = '';
$options = $user_profile['cf_classification']['options'];
# check if the $custom_field is in the options of user_profile['cf_classification']
# using the array_key_exist method

if (array_key_exists($custom_field, $options)) {
# to get the value of the custom field then you need to traverse
# the array for its value
$education = $options[$custom_field]['value'];
} else {
$education = "not found";
}

echo $education;

这将打印

Freshman

关于php - 如何比较内部数组键和值并在 PHP 中相应地设置变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com