0

I have an array that looks like this:

    [0] => Array
        (
            [name] => typeOfMusic
            [value] => this_music_choice
        )

    [1] => Array
        (
            [name] => myMusicChoice
            [value] => 9
        )

    [2] => Array
        (
            [name] => myMusicChoice
            [value] => 8
        )

I would like to reform this into something with roughly the following structure:

Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)

I have written the following but it doesn't work:

    foreach($originalArray as $key => $value) {
        if( !empty($return[$value["name"]]) ){
            $return[$value["name"]][] = $value["value"];
        } else {
            $return[$value["name"]] = $value["value"];
        }
    }

    return $return;

I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?

I'm getting nowhere with this and would appreciate a little help. Many thanks.

1
  • Would appreciate a heads up as to the reason for the mark downs on the question? It is concise and to the point showing due dilligence on my part. Am I missing something? Thanks. Commented Jul 31, 2014 at 18:32

3 Answers 3

3

You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.

Something like this:

$return = array();
foreach($originalArray as $data){
    if(!isset($return[$data['name']])){
        // This is the first time we've seen this name,
        // it's not in $return, so let's add it
        $return[$data['name']] = $data['value'];
    }
    elseif(!is_array($return[$data['name']])){
        // We've seen this key before, but it's not already an array
        // let's convert it to an array
        $return[$data['name']] = array($return[$data['name']], $data['value']);
    }
    else{
        // We've seen this key before, so let's just add to the array
        $return[$data['name']][] = $data['value'];
    }
}

DEMO: https://eval.in/173852

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

2 Comments

Great stuff. Many thanks for that. Not sure why I keep getting "marked down" for questions. It certainly discourages the use of the site as it appears that the only way to prevent "marking down" is to delete ones question as soon as it has an answer? Thank you Rocket for your excellent answer and thank you mxmul for your help also.
Glad I could help :-D Not sure why this question was marked down, I don't think it's a bad question. Maybe there is already a similar question with an answer? That's all I can think of as to why you'd be marked down.
1

Here's a clean solution, which uses array_reduce

$a = [
    [
        'name' => 'typeOfMusic',
        'value' => 'this_music_choice'
    ],
    [
        'name' => 'myMusicChoice',
        'value' => 9
    ],
    [
        'name' => 'myMusicChoice',
        'value' => 8
    ]
];

$r = array_reduce($a, function(&$array, $item){
    // Has this key been initialized yet?
    if (empty($array[$item['name']])) {
        $array[$item['name']] = [];
    }
    $array[$item['name']][] = $item['value'];
    return $array;
}, []);

1 Comment

Hi Ronni, this is a fantastic solution. Extremely succinct. I did look at the list of php array functions before posting the question to see if any looked like they could do the job but I didn't really see how to use array_reduce. I'm going to stick with 'accepting' Rockets answer as it is a simpler solution for me that (on my level) I understand so will make future fault finding easier. But thank you very much for your excellent solution. :-)
1
$arr = array(
    0 => array(
        'name'  => 'typeOfMusic',
        'value' => 'this_music_choice'
    ),
    1 => array(
        'name'  => 'myMusicChoice',
        'value' => 9
    ),
    2 => array(
        'name'  => 'myMusicChoice',
        'value' => 8
    )
);

$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
    if ($x == 0) {
        $newArr[$row[$$name]] = $row[$$value];
    } else {
        if (! is_array($newArr[$row[$$name]])) {
            $newArr[$row[$$name]] = array();
        }
        array_push($newArr[$row[$$name]], $row[$$value]);
    }       

    $x++;   
}

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.