0

I have an array $templates that looks like this:

        Array
(
    [0] => Array
        (
            [displayName] => First Template
            [fileName] => path_to_first_template
        )

    [1] => Array
        (
            [displayName] => Second Template
            [fileName] => path_to_second_template
        )

    [2] => Array
        (
            [displayName] => Third template
            [fileName] => path_to_third_template
        )

)

And I want to make it to look like this:

        Array
(
    [path_to_first_template] => First Template
    [path_to_second_template] => Second Template
    [path_to_third_template] => Third Template
)

That is, I want the fileName of the nested arrays to be the new array's key and displayName to be its value.

Is there a pretty way to do this without having to loop through the array. I had no luck searching, as I didn't know exactly what to search for.

3
  • 2
    Looping through the array is obviously required, even if it happens behind the scenes. Why not simply do that? Commented Sep 19, 2012 at 11:57
  • @Jon Yes, I know. It was an attempt to keep my code simple and avoid having to include my own little library if there was a simpler way to do it with built-in functions. :-) Commented Sep 19, 2012 at 12:02
  • There is a way to do it, but it's really debatable if it's any better than foreach. I show both in my answer. Commented Sep 19, 2012 at 12:04

3 Answers 3

3

Here's a classic foreach in action:

$result = array();
foreach($array as $row) {
    $result[$row['fileName']] = $row['displayName'];
};

Here's a "clever" way to do it:

$result = array();
array_walk($array, function($row) use (&$result) {
    $result[$row['fileName']] = $row['displayName'];
});

As you can see, the second approach is not really better than the first one. The only advantage is that theoretically you can pile upon the second form because it is a single expression, but in practice it's a long enough expression already so you wouldn't want to do that.

Sign up to request clarification or add additional context in comments.

Comments

2

Loop in your array and make a new one:

$newArray = array();
foreach($array as $val){
    $newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);

Comments

0
$ret = array()
foreach ($templates as $template) {
    $ret[$template["fileName"]] = $template["displayName"];
}

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.