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?

1
  • You array have not 2 key Commented Dec 15, 2017 at 3:16

3 Answers 3

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

Comments

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

1 Comment

the key of the answer is to check if it's an array with is_array. thanks
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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.