PHP/Data Structure/extract

Материал из Web эксперт
Перейти к: навигация, поиск

Add the prefix pts to each array key and then make each variable that results into a reference.

 
<?php 
$points = array("home" => 21, "away" => 13); 
extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts"); 
$pts_home -= 4; 
$pts_away += 6; 
printf("<p>%s</p>", var_export($points, TRUE)); 
?>



extract( ) function converts elements into variables

 
//int extract ( array arr [, int options [, string prefix]] )
<?
    $Wales = "Wales";
    $capitalcities = array("England"=>"London","Scotland"=>"Edinburgh", "Wales"=>"Cardiff");
    extract($capitalcities);
    print $Wales;
?>



Extracting Values from Arrays with extract()

 
<?php 
$customer = array("first" => "R", "last" => "W", "age" => 24, ); 
extract($customer); 
print "<p>$first $last is $age years old.</p>"; 
extract($customer, EXTR_PREFIX_ALL, "cust"); 
print "<p>$cust_first $cust_last is $cust_age years old.</p>"; 
?>



extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts");

 
<?php
  $points = array("home" => 21, "away" => 13);
  extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts");
  $pts_home -= 4;
  $pts_away += 6;
  printf("<pre>%s</pre>", var_export($points, TRUE));
?>



extract($scores, EXTR_PREFIX_ALL, "score");

 
<?php
  $scores = array(91, 56, 87, 79);
  extract($scores, EXTR_PREFIX_ALL, "score");
  print "<p>$score_0</p>";
  print "<p>$score_1</p>";
  print "<p>$score_2</p>";
  print "<p>$score_3</p>";
?>



Using extract on an associative array

 
<?php
$shapes = array("S" => "Cylinder",
                "N" => "Rectangle",
                "A" => "Sphere",
                "O" => "Sphere",
                "P" => "Rectangle");
extract($shapes);
echo $Apple;
echo "<br />";
echo $Notepad;
?>



Using extract with the EXTR_PREFIX_ALL directive

 
<?php
$Apple="Computer";
$shapes=array("S" => "Cylinder",
              "N" => "Rectangle",
              "A" => "Sphere",
              "O" => "Sphere",
              "P" => "Rectangle");
extract($shapes,EXTR_PREFIX_ALL,"shapes");
echo "Apple is $Apple.<br />";
echo "Shapes_Apple is $shapes_Apple";
echo "<br />";
echo "Shapes_NotePad is $shapes_NotePad";
?>



Using EXTR_PREFIX_ALL on a numeric array

 
<?php
$shapes=array( "Cylinder",
               "Rectangle");
extract($shapes,EXTR_PREFIX_ALL,"shapes");
echo "Shapes_0 is $shapes_0
 <br />";
echo "Shapes_1 is $shapes_1
";
?>