Harea Costicla
Harea Costicla

Reputation: 817

Create a correct array in php

I have the following code :

public static function getNatureAndSuffix()
{
    foreach (Finder::load('all.yml') as $s => $c) {
        $a_games[] = array($c['n'] => $s);
    }
    return $a_games;
}

The result is :

Array(
[90] => Array
    (
        [731] => Test1
    )

[91] => Array
    (
        [732] => Test2
    )

[92] => Array
    (
        [735] => Test3
    )
  )

But I want to get :

Array(
[731] => Test1
[732] => Test1
[735] => Test3
)

So the idea is to obtain an array key=>value. Can you help me please ? Thx in advance

Upvotes: 0

Views: 54

Answers (2)

Firewizz
Firewizz

Reputation: 813

public static function getNatureAndSuffix()
{
    foreach (Finder::load('all.yml') as $s => $c) {
        $a_games[$c['n']] = $s;
    }
    return $a_games;
}

explanation:

with: array($c['n'] => $s) you are creating a new array in a array($a_games) what you don't want.

So if you id the index of the first array with the id you get from the loop and give it the value you get from the loop you end up with only a single array. So the line would be:

$a_games[$c['n']] = $s;

Upvotes: 4

Sougata Bose
Sougata Bose

Reputation: 31739

You are setting a new array with those value.

By $a_games[] = array($c['n'] => $s);, it would set as nested array.

Simply do -

$a_games[$c['n']] = $s;

Then the key would be $c['n'] & value be $s in $a_games.

Or you can also do without loop -

$temp = Finder::load('all.yml');
$a_games = array_combine(
array_keys($temp), 
array_column($temp, 'n')
);

Note : array_column() is supported PHP >= 5.5

Upvotes: 1

Related Questions