Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

syntax for foreach in php

what does this syntax means in php

foreach ( $meta as $t => $data )

what does $t => $data mean in the above.

because foreach is basically (example from w3school)

  <?php
  $colors = array("red","green","blue","yellow");
  foreach ($colors as $value)
    {
    echo "$value <br>";
    }
  ?> 

it the above case $value represents $t => $data

$colors represents $meta

the array $meta is as follows

    $meta = Array(
    'facebook' => Array(
      'title'   => 'og:title',
      'type'   => 'og:type',
      'url'   => 'og:url',
      'thumbnail'  => 'og:image',
      'width'   => 'og:image:width',
      'height'  => 'og:image:height',
      'sitename'  => 'og:site_name',
      'key'   => 'fb:admins',
      'description' => 'og:description'
    ),
    'twitter' => Array(
      'card'   => 'twitter:card',
      'description' => 'twitter:description',
    )
      );

then what is $t and what is $data

also if i want to get 'title' in 'facebook' as a seprate key how to do it. ie. will

  $t => $data => $final work

  $t = facebook or twitter
  $data = title etc
  $final = og:title etc
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use foreach it loops over array's items. Base syntax is:

foreach ($array as $item) {
  // first loop:  $item=foo
  // second loop: $item=bar
}

you can use extended syntax

foreach ($array as $key => $item) {}

which allows you to get item's key in $key variable. For example:

$array = array('foo', 'bar');
foreach ($array as $key => $item) {
  // first loop:  $key=0, $item=foo
  // second loop: $key=1, $item=bar
}

$array does not contain keys, so in $key variable you have numbers (starts with 0).

If keys are defined (associative arrays), $key will take defined key value:

$array = array('key1' => 'foo', 'key2' => 'bar');
foreach ($array as $key => $item) {
  // first loop:  $key=key1, $item=foo
  // second loop: $key=key2, $item=bar
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...