0

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.

3
  • Did you tried $data['worker_id']? What kind of error did you get? Commented Mar 31, 2020 at 7:39
  • @WannyMiarelli yes i get error Trying to get property 'worker_id' of non-object Commented Apr 1, 2020 at 2:01
  • yes this is because it is an array and not an object, the -> accessor is only for objects, with arrays you should use the index $data['index']. Commented Apr 1, 2020 at 7:23

2 Answers 2

1
<?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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

you can badge my answer.
you can vote and check it. and click on answer button.
done, i'm so embarrassed don't see the check button
0

While He Zhi Yong answer may work to me it is more correct to access it as an array instead of an object.

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

foreach ($request as $data)
{
    echo $data['worker_id'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.