0

With PHP, I have list of Object. Each object have id field :

$myArray = [
    0 => Object{
        'id' => 1,
        'title' => 'My title 1'
    },
    1 => Object{
        'id' => 2,
        'title' => 'My title 2'
    },
    2 => Object{
        'id' => 6,
        'title' => 'My title 6'
    }
]

I want to set array key from id object without additional foreach. I want this result :

$myArray = [
    1 => Object{
        'id' => 1,
        'title' => 'My title 1'
    },
    2 => Object{
        'id' => 2,
        'title' => 'My title 2'
    },
    6 => Object{
        'id' => 6,
        'title' => 'My title 6'
    }
]

I think it's possible with array_map but I don't know how to do it. I tried this but it returns sub array :

$newArray = array_map(function($entry) {
    return [$entry->id => $entry];
}, $myArray);

// return :

[
    0 => [
        1 => Object{
            'id' => 1,
            'title' => 'My title 1'
        },
    ],
    1 => [
        2 => Object{
            'id' => 2,
            'title' => 'My title 2'
        },
    ],
    2 => [
        6 => Object{
            'id' => 6,
            'title' => 'My title 6'
        }
    ]
]
1
  • array_map will return a new array. You may try with array_walk Commented Apr 21, 2020 at 16:34

2 Answers 2

2
$myArray = array_column($myArray, null, 'id');
Sign up to request clarification or add additional context in comments.

2 Comments

This is better than the solution I was going to suggest, which combines array_column with array_combine.
This solution is cool
0

Try using this

array_combine(array_column($myArray, 'id'), $myArray);

This way you will make the ID as the key and keep all the array related to id as the value for this index.

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.