简体   繁体   中英

How to access array elements

I am getting this as var_dump:

array(1) {
  [0]=>
  array(4) {
    ["num"]=>
    string(1) "1"
    ["yyyy"]=>
    string(4) "2013"
    ["mm"]=>
    string(2) "12"
    ["dd"]=>
    string(2) "11"
  }
}

How to access the array elements?

Let's assume your array is $arr, you can do

echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];

As you are fetching from a database, you will receive an array for each result row, and within each array will be another array of columns. you can use a foreach() loop to iterate over the data, as follows:

foreach($arr as $row) {
    echo $row['num'] . ':' . $row['yyyy'] . '-' . $row['mm'] . '-' . $row['dd'] . "\n";
}

Please have a look at the official PHP Doc article about arrays .

In your case:

$yourArrayVariable[0]['yyyy']

Will let you access the element with value 2013 .

Or if you have an undefined number of array entries you can iterate over it with either foreach or for .

foreach($yourArrayVariable as $key => $value) {
    echo $key , ': ' , $value , '<br>';
}

or if you have only numeric indeces without a gap:

$arrCount = count($yourArrayVariable);

for($i = 0; $i < $arrCount; ++$i) {
   echo $i , ': ' , $arrCount[0] , '<br>';
}

You can get the value using echo $array[0]['num']; gives output as 1

    $array ='your array data here';
    foreach($array as $key=>$value) {
        echo "num: ". $value['num'] . "/yyyy: ". $value['yyyy']. " /mm: ". $value['mm'] . " /dd: ". $value['dd'] . "<br>";
    }

try this

foreach($array as $value) {
    foreach($value as $k=>$v) {
        echo $k . " : " . $v .'<br/>';
    }
    echo '<hr>';
}

store array in a variable like

$arr =array(1) {
  [0]=>
  array(4) {
    ["num"]=>
    string(1) "1"
    ["yyyy"]=>
    string(4) "2013"
    ["mm"]=>
    string(2) "12"
    ["dd"]=>
    string(2) "11"
  }
}

for access array elements you have to use following code

echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];o $arr[0]['num']
$arr =Array(
  0=>array(
    "num"=>"1",
    "yyyy"=>"2013",
    "mm"=>"12",
    "dd"=>"11",
  )
 );


 foreach ($arr as $value) {    
     echo "num: ".$value["num"];
     echo "yyyy: ".$value["yyyy"];
     echo "mm: ".$value["mm"];
     echo "dd: ".$value["dd"];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM