Skip to content
Advertisement

get object from multidimensional array php

I have multidimensional array like this

array:2 [
  0 => array:2 [
    "worker_id" => "1"
    "salary" => "100000"
  ]
  1 => array:2 [
    "worker_id" => "2"
    "salary" => "80000"
  ]
]

i try get the object but didn’t work

foreach ($request->salary as $data)
{
    ($data->worker_id);
}

Thanks a lot.

Advertisement

Answer

<?php

function arr2Object($arr) {
    if (is_array($arr)) {        
        return (object) array_map(__FUNCTION__, $arr);
    }
    else {        
        return $arr;
    }
}

$request = [ ["worker_id" => "1", "salary" => "100000"], ["worker_id" => "2", "salary" => "80000"]];

$obj = arr2Object($request);

foreach ($obj as $data) {
    echo $data->worker_id;
    echo $data->salary;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement