0

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

2 Answers 2

4
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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.