0

I need some help restructuring an array that I get from an API. The current format is hard for me to work with so I want to change it for something more workable.

I have the following array:

[
    'attributes' => [
        ['attribute' => 'Healing', 'modifier' => 179],
        ['attribute' => 'Toughness', 'modifier' => 128],
        ['attribute' => 'ConditionDamage', 'modifier' => 179],
    ]
]

and I want to turn it into this:

[
    'attributes' => [
        'Healing' => 179,
        'Toughness' => 128,
        'ConditionDamage' => 179,
    ]
]
0

3 Answers 3

1

If you're using PHP >= 5.5

$array['attributes'] = array_column(
    $array['attributes'],
    'attribute',
    'modifier'
);

else

$array['attributes'] = array_walk(
    $array['attributes'],
    function (&$value) {
        $value[$value['attribute']] = $value['modifier'];
        unset($value['attribute'], $value['modifier']);
    }
);
Sign up to request clarification or add additional context in comments.

Comments

1

Using PHP >= 5.5, you can take advantage of array_column(), in conjunction with array_combine().

$new_arr = array_combine(array_column($arr, 'attribute'), array_column($arr, 'modifier'));

See demo


Otherwise, a simple foreach will work:

foreach ($arr as $ar) {
    $new_arr[$ar['attribute']] = $ar['modifier'];
}

See demo

Comments

1
function flattenAPIarray($APIArray)
{
    $flatArray = [];

    foreach($APIArray as $element)
    {
        $key = array_keys($element);
        $flatArray[$element[$key[0]]] = $element[$key[1]];
    }

    return $flatArray;
}

Try this function, I wrote for you. It's not generalized in any manner, but works fine with your multidimensional associative array. The clue is to use the array_keys() function, as you don't have any index to iterate using the foreach loop.

Hope that helps! (It's my first answer - be kind :o)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.