[英]Create another array of same array - only one key value. PHP
I am trying to create a array from one entry inside another array. 我正在尝试从另一个数组中的一个条目创建一个数组。 So the prosess is that i get an array from frontend that looks like this:
因此,麻烦的是我从前端得到了一个数组,如下所示:
[{
"account_id": "123456789",
"month_id": 201808,
"month_budget": 11
}, {
"account_id": "111222",
"month_id": 201809,
"month_adops_forecast": 11
}]
now in my backend i must retrive either "month_budget" or "month_adops_forecast", i have created an if statement in backend like this: 现在在后端,我必须检索“ month_budget”或“ month_adops_forecast”,我已经在后端创建了一个if语句,如下所示:
if (isset($data['month_budget'])) {
$metric = "month_budget =". $data['month_budget'];
} else if (isset($data['month_adops_forecast'])){
$metric = "month_adops_forecast =". $data['month_adops_forecast'];
}else {
return false;
}
As you can see i create it as an string
, but i would want this "metric"
in an own array i create. 如您所见,我将其创建为
string
,但是我希望在自己创建的数组中使用此"metric"
。 I tried to retrive both key and value, but this only gave me the value because it is inside an if (isset($data['month_budget'])) {
so by saying $data['month_budget']
i cannot retrive the key 我试图同时获取键和值,但这仅给了我价值,因为它位于
if (isset($data['month_budget'])) {
所以我说$data['month_budget']
我无法获取该键
What would be the best way to retrive this data? 检索此数据的最佳方法是什么?
Wanted result: 想要的结果:
$data = same array as it is $ data =相同的数组
$metric = month_budget or month_adops_forecast $ metric = month_budget或month_adops_forecast
$metric = array('month_adops_forecast' => 11);
OR 要么
$metric = array('month_budget' => 11);
You can use this: 您可以使用此:
if (isset($data['month_budget'])) {
$metric['month_budget'] = $data['month_budget'];
} else if (isset($data['month_adops_forecast'])){
$metric['month_adops_forecast'] = $data['month_adops_forecast'];
} else {
return false;
}
This $metric = "month_budget =". $data['month_budget']
此
$metric = "month_budget =". $data['month_budget']
$metric = "month_budget =". $data['month_budget']
notation cannot be used to create arrays, you have to either set the key using $array['key']
or $array = array('key' => 'value')
among other ways, of course, being this ones around the most common. $metric = "month_budget =". $data['month_budget']
表示法不能用于创建数组,您必须使用$array['key']
或$array = array('key' => 'value')
,例如当然,这是最常见的。
I'm assuming you were trying the last one. 我假设您正在尝试最后一个。
If I got your answer right, to get the result you expect you can use this: 如果我的回答正确,要获得预期的结果,可以使用以下方法:
if (isset($data['month_budget'])) {
$metric['month_budget'] = $data['month_budget']);
} else if (isset($data['month_adops_forecast'])){
$metric['month_adops_forecast'] = $data['month_adops_forecast']);
}else {
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.