php get single key value array from mutidimanal arraya code example

Example 1: get key by value array php

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

Example 2: php collapse common columns in associative array

/* Collapse on common columns which is also the new key e.g.
([0] => [[id] => 1234, [firstName] => "foo", [1] => [[id] => 1234, [lastName] => "bar")
will become ([1234] => [[firstName] => "foo", [lastName]="bar"]
Credit to https://stackoverflow.com/users/762073/xdazz
*/
$result = array();
foreach ($data as $element) {
    $result[$element['id']][] = $element;// [] appends to the array if it already exists
}

Tags:

Php Example