Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...