Asim
Asim

Reputation: 976

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:

    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. 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

What would be the best way to retrive this data?

Wanted result:
$data = same array as it is
$metric = month_budget or month_adops_forecast

$metric = array('month_adops_forecast' => 11);

OR

$metric = array('month_budget' => 11);

Upvotes: 0

Views: 76

Answers (2)

Daniele Scillia
Daniele Scillia

Reputation: 129

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;
}

Upvotes: 0

Rafael
Rafael

Reputation: 1535

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'] 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.

I'm assuming you were trying the last one.

Upvotes: 1

Related Questions