Search code examples
phpassociative-arrayarray-map

Separating data from an associative array index wise in php


I know that i will be using array_map for this but the issue it keeps saying

notice Undefined index: DeviceID.....

I am trying to Separate DeviceID as $key and all its values as $value

//Code
$output = array_map(null,$getTheHistoricData['DeviceID']);

//Array
array (size=4112)
0 => 
array (size=5)
  'DeviceID' => string '1' (length=1)
  'DeviceTimestamp' => string '2018-09-22 00:00:11' (length=19)
  'LineTemp' => string '22.2148' (length=7)
  'LineCurrent' => string '232.562' (length=7)
  'RxRSSI' => string '0' (length=1)
1 => 
array (size=5)
  'DeviceID' => string '1' (length=1)
  'DeviceTimestamp' => string '2018-09-22 00:00:33' (length=19)
  'LineTemp' => string '22.2154' (length=7)
  'LineCurrent' => string '234.672' (length=7)
  'RxRSSI' => string '0' (length=1)
2 => 
array (size=5)
  'DeviceID' => string '1' (length=1)
  'DeviceTimestamp' => string '2018-09-22 00:00:55' (length=19)
  'LineTemp' => string '22.2094' (length=7)
  'LineCurrent' => string '233.954' (length=7)
  'RxRSSI' => string '0' (length=1)
and so on

Solution

  • You should use array_map() as shown in bottom to do this work.

    $output = array_map(function($val){
        return $val['DeviceID'];
    }, $getTheHistoricData);
    

    Check result in demo

    Also you can use array_column() instead

    $output = array_column($getTheHistoricData, 'DeviceID');