0

I have an array like this:

array(4) {
  [0]=>
  array(1) {
    ["id"]=>
    string(3) "207"
  }
  [1]=>
  array(1) {
    ["id"]=>
    string(4) "1474"
  }
  ["date"]=>
  string(39) "Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)"
  ["content"]=>
  string(4) "test"
}

I know how to access date and content but I don't know how to access id. I tried using this loop:

for ($i=0; $i < count($data); $i++){
     var_dump($data[$i]['id']);
}

But I got error

Undefined offset: 2 for content and date.

How can I access those ids?

aaa
  • 857
  • 4
  • 25
  • 46
Abaij
  • 853
  • 2
  • 18
  • 34

3 Answers3

2

You can use foreach and inside foreach add a condition if it's an array

Solution:

$data = array(
    array('id' => '207'),
    array('id' => '1474'),
    'date' => 'Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)',
    'content' => 'test'
);

foreach($data as $key => $val){
    if(is_array($val)){
        //We can use foreach instead of printin it out directly 
        //if this array will have more value
        //If not just use $val['id']
        foreach($val as $k => $v){
            echo $k . ' = ' . $v . '<br />';
        }
    }else{
        echo $key . ' = ' . $val . '<br />';
    }
}

OUTPUT

id = 207
id = 1474
date = Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)
content = test
Bluetree
  • 1,324
  • 2
  • 8
  • 25
1

With a foreach, you then check its an array. If you don't want date and content then remove the else.

<?php
$arr = [
    ['id' => '207'],
    ['id' => '1474'],
    'date' => 'Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)',
    'content' => 'test'
];

foreach ($arr as $key => $value) {
    if (is_array($value)) {
        echo $value['id'];
    } else {
        echo $value;
    }
}

// 2071474Fri Dec 08 2017 00:00:00 GMT+0700 (WIB)test

https://3v4l.org/TOnnH

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
1

The loop you've written is trying to access the keys $data[2] and $data[3], which do not exist. You should be able to get these id keys with $data[0]["id"] and $data[1]["id"]. Try something like this, with foreach loops.

foreach ($data as $key => $val) {
    echo ((is_array($val)) ? $val["id"] : $val);
}
Tanner Babcock
  • 3,232
  • 6
  • 21
  • 23