PHP/Data Structure/extract — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 10:02, 26 мая 2010
Содержание
- 1 Add the prefix pts to each array key and then make each variable that results into a reference.
- 2 extract( ) function converts elements into variables
- 3 Extracting Values from Arrays with extract()
- 4 extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts");
- 5 extract($scores, EXTR_PREFIX_ALL, "score");
- 6 Using extract on an associative array
- 7 Using extract with the EXTR_PREFIX_ALL directive
- 8 Using EXTR_PREFIX_ALL on a numeric array
Add the prefix pts to each array key and then make each variable that results into a reference.
<source lang="html4strict">
<?php $points = array("home" => 21, "away" => 13); extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts"); $pts_home -= 4; $pts_away += 6;
printf("%s
", var_export($points, TRUE));?>
</source>
extract( ) function converts elements into variables
<source lang="html4strict">
//int extract ( array arr [, int options [, string prefix]] ) <?
$Wales = "Wales"; $capitalcities = array("England"=>"London","Scotland"=>"Edinburgh", "Wales"=>"Cardiff"); extract($capitalcities); print $Wales;
?>
</source>
Extracting Values from Arrays with extract()
<source lang="html4strict">
<?php $customer = array("first" => "R", "last" => "W", "age" => 24, ); extract($customer);
print "$first $last is $age years old.
";extract($customer, EXTR_PREFIX_ALL, "cust");
print "$cust_first $cust_last is $cust_age years old.
";?>
</source>
extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts");
<source lang="html4strict">
<?php
$points = array("home" => 21, "away" => 13); extract($points, EXTR_REFS|EXTR_PREFIX_ALL, "pts"); $pts_home -= 4; $pts_away += 6;printf("
%s", var_export($points, TRUE));
?>
</source>
extract($scores, EXTR_PREFIX_ALL, "score");
<source lang="html4strict">
<?php
$scores = array(91, 56, 87, 79); extract($scores, EXTR_PREFIX_ALL, "score");print "
$score_0
"; print "$score_1
"; print "$score_2
"; print "$score_3
";?>
</source>
Using extract on an associative array
<source lang="html4strict">
<?php $shapes = array("S" => "Cylinder",
"N" => "Rectangle", "A" => "Sphere", "O" => "Sphere", "P" => "Rectangle");
extract($shapes);
echo $Apple;
echo "
";
echo $Notepad;
?>
</source>
Using extract with the EXTR_PREFIX_ALL directive
<source lang="html4strict">
<?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.
";
echo "Shapes_Apple is $shapes_Apple";
echo "
";
echo "Shapes_NotePad is $shapes_NotePad";
?>
</source>
Using EXTR_PREFIX_ALL on a numeric array
<source lang="html4strict">
<?php $shapes=array( "Cylinder",
"Rectangle");
extract($shapes,EXTR_PREFIX_ALL,"shapes"); echo "Shapes_0 is $shapes_0
";
echo "Shapes_1 is $shapes_1 "; ?>
</source>