0

I have an array of arrays like this :

array(2) {
  [0]=>
  array(2) {
    ["ssmenu_id"]=>
     string(1) "5"
    ["ssmenu_titre"]=>
    string(10) "newsletter"
  }
  [1]=>
  array(2) {
    ["ssmenu_id"]=>
    string(1) "6"
    ["ssmenu_titre"]=>
    string(9) "sous-test"
  }
}

How do I get from that to :

array(2) {
5 => "newsletter",
6 => "sous-test"
}

I have tried various things using foreach, for, list... can't get my head around it.

thiebo
  • 1,339
  • 1
  • 17
  • 37

4 Answers4

2
$res = array();
foreach($arr as $item){
      $res[$item['ssmenu_id']] = $item['ssmenu_titre'];
}

var_dump($res);

output:

array(2) {
  [5]=>
  string(10) "newsletter"
  [6]=>
  string(9) "sous-test"
}
Ceeee
  • 1,392
  • 2
  • 15
  • 32
2

With PHP 5 >= 5.5.0 and PHP 7, you can use array_column():

$array = [
    [
        "ssmenu_id" => 5,
        "ssmenu_titre" => "newsletter",

    ],
    [
        "ssmenu_id" => 6,
        "ssmenu_titre" => "sous-test",

    ],

];

print_r(array_column($array, 'ssmenu_titre', 'ssmenu_id'));

/* Output:

Array
(
    [5] => newsletter
    [6] => sous-test
)

*/
ax.
  • 58,560
  • 8
  • 81
  • 72
1

try below solution:

$array = array(
    array(
        "ssmenu_id" => 5,
        "ssmenu_titre" => "newsletter",

    ),
    array(
        "ssmenu_id" => 6,
        "ssmenu_titre" => "sous-test",

    ),

);

$res = array();
foreach($array as $item){
        $res[$item['ssmenu_id']] = $item['ssmenu_titre'];
}

print_r($res);

output:

Array
(
    [5] => newsletter
    [6] => sous-test
)
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
0

I'd suggest using the array_flip() function. As this is a multi-dimensional array you will need to loop through it. There are examples in the comments to the PHP page I linked to, but it's a pretty trivial task when using this function.

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76