Saya memiliki array yang berisikan beberapa object dan saya ingin melakukan konversi object-object tersebut menjadi array di dalam array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Array
(
    [0] => stdClass Object
        (
            [id_unit] => 52
            [id_jabatan] => 574
        )

    [1] => stdClass Object
        (
            [id_unit] => 52
            [id_jabatan] => 41
        )

    [2] => stdClass Object
        (
            [id_unit] => 7
            [id_jabatan] => null
        )

    [3] => stdClass Object
        (
            [id_unit] => 9
            [id_jabatan] => null
        )

    [4] => stdClass Object
        (
            [id_unit] => 11
            [id_jabatan] => null
        )
)

Dengan menggunakan perintah json_decode(json_encode($myObj), true); hasilnya seperti di bawah ini.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Array
(
    [0] => Array
        (
            [id_unit] => 52
            [id_jabatan] => 574
        )

    [1] => Array
        (
            [id_unit] => 52
            [id_jabatan] => 41
        )

    [2] => Array
        (
            [id_unit] => 7
            [id_jabatan] => null
        )

    [3] => Array
        (
            [id_unit] => 9
            [id_jabatan] => null
        )

    [4] => Array
        (
            [id_unit] => 11
            [id_jabatan] => null
        )
)

Bonus!

Berikutnya, saya ingin mem-filter hanya id_unit bernilai 52 yang ditampilkan. Caranya menggunakan fungsi array_filter() yang disediakan oleh PHP.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

<?php

$array = array(
    array('id_unit' => '52', 'id_jabatan' => '574'),
    array('id_unit' => '52', 'id_jabatan' => '41'),
    array('id_unit' => '7', 'id_jabatan' => null),
    array('id_unit' => '9', 'id_jabatan' => null),
    array('id_unit' => '11', 'id_jabatan' => null),
);

$id_unit_filter = '52';

$result = array_filter($array, function ($item) use ($id_unit_filter) {
    if ($item['id_unit'] === $id_unit_filter) {
        return true;
    }
    return false;
});

Hasilnya seperti di bawah ini.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Array
(
    [0] => Array
        (
            [id_unit] => 52
            [id_jabatan] => 574
        )

    [1] => Array
        (
            [id_unit] => 52
            [id_jabatan] => 41
        )

Referensi

  1. Convert an object to associative array in PHP
  2. How to Filter Multidimensional Array by Key Value in PHP