PHP/Data Structure/Associate Array

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

An array called $computers with numeric and string keys

   <source lang="html4strict">

<? $computers["t"] = "A"; $computers[2] = "B"; $computers["A"] = "C"; ?>

 </source>
   
  


An array called $vegetables with string keys

   <source lang="html4strict">

<? $vegetables["corn"] = "yellow"; $vegetables["beet"] = "red"; $vegetables["carrot"] = "orange"; ?>

 </source>
   
  


Argument Swapping

   <source lang="html4strict">

<?php $dates = array(

     array( "mon"=> 12, "mday"=>25, "year"=>2001 ),
     array( "mon"=> 5, "mday"=>23, "year"=>2000 ),
     array( "mon"=> 10, "mday"=>29, "year"=>2001 )
     );

$format = include ("local_format.php"); foreach ($dates as $date) {

 printf( "$format", $date["mon"], $date["mday"], $date["year"] );

} ?>

 </source>
   
  


array_intersect_assoc: Computes the intersection of arrays with additional index check

   <source lang="html4strict">

<?php

  $array1 = array("OH" => "Ohio", "CA" => "California", "HI" => "Hawaii");
  $array2 = array("50" => "Hawaii", "CA" => "California", "OH" => "Ohio");
  $array3 = array("TX" => "Texas", "MD" => "Maryland", "OH" => "Ohio");
  $intersection = array_intersect_assoc($array1, $array2, $array3);
  print_r($intersection);

?>

      </source>
   
  


array_key_exists

   <source lang="html4strict">

<?php

  $state["Delaware"] = "December 7, 1787";
  $state["Pennsylvania"] = "December 12, 1787";
  $state["Ohio"] = "March 1, 1803";
  if (array_key_exists("Ohio", $state)) echo "Ohio joined the Union on $state[Ohio]";

?>

      </source>
   
  


array_keys: Return all the keys of an array

   <source lang="html4strict">

<?php

  $state["Delaware"] = "December 7, 1787";
  $state["Pennsylvania"] = "December 12, 1787";
  $state["New Jersey"] = "December 18, 1787";
  $keys = array_keys($state);
  print_r($keys);
  // Array ( [0] => Delaware [1] => Pennsylvania [2] => New Jersey )

?>

      </source>
   
  


Arrays Using Associative Array Notation

   <source lang="html4strict">

<html> <head>

    <title>Associative Array Notation</title>

</head> <body> <?php

    $cars = array(
        "1"       => array ("A", "B", "C"),
        "2"      => array ("D", "E", "F", "G"),
        "3"    => array ("H", "I")
    );
    ob_start();
    var_dump($cars);
    $cars_var_dump = ob_get_contents();
    ob_end_clean();
  
print("
" . $cars_var_dump . "
");

?> </body> </html>

      </source>
   
  


Array to object

   <source lang="html4strict">

<?php $arr = array(

 "abc" => "abc",
 "def" => 123.5,
 "ghi" => array(1,2,3),
 0 => "def"

); $key = "abc"; $obj = (object) $arr; echo "First value = $obj->abc\n"; echo "Second value = $obj->def\n"; echo "Third value = $obj->ghi\n"; ?>

 </source>
   
  


array_values: Return all the values of an array

   <source lang="html4strict">

<?php

  $population = array("Ohio" => "11,421,267", "Iowa" => "2,936,760");
  $popvalues = array_values($population);
  print_r($popvalues);
  // Array ( [0] => 11,421,267 [1] => 2,936,760 )

?>

      </source>
   
  


Assigning and Comparing

   <source lang="html4strict">

<?php $a = array(0=>1,2=>"orange","id"=>7,"name"=>"John" ); print_r($a); ?>

 </source>
   
  


Associative Arrays

   <source lang="html4strict">
<?php
 $emp_det [Name] = "Name";
 $emp_det [Age] = "2";
 $emp_det [Code] = "8";
 $emp_det [Designation] = "System Administrator";
 
 echo $emp_det[Name];  
 $emp_det = array (Name => "Name", Age => "24", Code => "System Administrator");
 echo $emp_det[Name];  
?>
          
      </source>
   
  


Building an array of defaults

   <source lang="html4strict">

if ($_POST["_submit_check"]) {

   $defaults = $_POST;

} else {

   $defaults = array("delivery"  => "yes",
                     "size"      => "medium",
                     "main_dish" => array("taro","tripe"),
                     "sweet"     => "cake");

}

 </source>
   
  


Creates an array that assigns keys 1 through 7 to the days of the week.

   <source lang="html4strict">

<?

   $days = array(1=>"Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday");

?>

 </source>
   
  


Creates an array with keys "a", "b" and "c with values of 1, 2 and 3 as well as keys 0, 1 and 2 with values "a", "b", and "c"

   <source lang="html4strict">

<?

   $myarray = array("a"=>1, "a", "b"=>2, "b", "c"=>3, "c");

?>

 </source>
   
  


Creating an associative array of shapes

   <source lang="html4strict">

<?php $shapes = array("S" => "Cylinder",

               "N" => "Rectangle",
               "A" => "Sphere",
               "O" => "Sphere",
               "P" => "Rectangle");

?>

 </source>
   
  


Creating Arrays

   <source lang="html4strict">

<?php

 $my_array = array();
 $pets = array("A", "S", "B", "W");
 $person = array("B", "J", 24, "CA");
 $customer = array("first" => "Bill", "last" => "Jones","age" => 24, "state" => "CA");
print "

Pet number 1 is named "$pets[0]".

\n"; print "

The person"s age is $person[2].

\n"; print "

The customer"s age is {$customer["age"]}.

\n";

?>

 </source>
   
  


Displaying one value from an array

   <source lang="html4strict">

<?php $shapes = array("S" => "Cylinder",

               "N" => "Rectangle",
               "A" => "Sphere",
               "O" => "Sphere",
               "P" => "Rectangle");

print "A notepad is a {$shapes["Notepad"]}."; ?>

 </source>
   
  


foreach statement is used to loop through an associative array

   <source lang="html4strict">

<?php $emp_det = array (Name => "A",

                 Age => "2" ,
                 Code =>"8",
                 Designation => "Administrator");

foreach ($emp_det as $key=>$temp) {

  echo "$key = $temp","\n";

} ?>


      </source>
   
  


key: Fetch a key from an associative array

   <source lang="html4strict">

<?php

  $capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines","Arizona" => "Phoenix");
echo "

Can you name the capitals of these states?

";
  while($key = key($capitals)) {
     echo $key."
"; next($capitals); }

?>

      </source>
   
  


Looping Through an Associative Array with foreach

   <source lang="html4strict">

<html> <head> <title>Looping Through an Associative Array with foreach</title> </head> <body> <?php $character = array (name=>"Joe",

                   occupation=>"Programmer",
                   age=>30,
                   "Learned language "=>"Java"

); foreach ( $character as $key=>$val ){

   print "$key = $val
";

} ?> </body> </html>

      </source>
   
  


Obtaining Array Keys and Values

   <source lang="html4strict">

<?php function array_display($array, $pre=FALSE){

   $tag = $pre ? "pre" : "p"; 
   printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag); 

} $fruits = array("red" => "apple", "yellow" => "banana", "green" => "lime"); $colors = array_keys($fruits); $flavors = array_values($fruits);

array_display($fruits); array_display($colors); array_display($flavors); ?>

 </source>
   
  


Obtaining Array Keys with a Given Value

   <source lang="html4strict">

<?php

 $countries = array( "USA" => "English", "Spain" => "Spanish",
                     "France" => "French", "Argentina" => "Spanish");
                     

 function array_get_keys($search, $array)
 {
   $keys = array(); 
   
   foreach($array as $key => $value) 
     if($value == $search) 
       $keys[] = $key; 
   
   if(count($keys) == 0) 
     $keys = FALSE; 
 
   return $keys;
 }
 
 $language = "Spanish";
 $spoken = array_get_keys($language, $countries);
 
printf("

Countries where %s is spoken: %s.

\n",
         $language,
         $spoken ? implode(", ", $spoken) : "None");
 
 $language = "Tagalog";
 $spoken = array_get_keys($language, $countries);
 
printf("

Countries where %s is spoken: %s.

\n",
         $language,
         $spoken ? implode(", ", $spoken) : "None");

?>

 </source>
   
  


One-based array index

   <source lang="html4strict">

<html>

<head>
 <title>One-based array index</title>
</head>
<body>
    <?php $arr = array( 1 => "1st", "2nd", "3rd", "4th", "5th" ); for( $i = 1; $i <= sizeof($arr); $i++ ) { echo("Position $i - Element value: $arr[$i]
    "); }  ?>
</body>

</html>

 </source>
   
  


print_r: output associate array

   <source lang="html4strict">

<?php $states = array ( "Ohio" => array ("population" => "11,353,140", capital => "Columbus"), "Nebraska" => array("population" => "1,711,263", capital => "Omaha") ) print_r($states); ?>


      </source>
   
  


Reference the assiciate array element

   <source lang="html4strict">

<? $birthdays["K"] = "1988-04-12"; $birthdays["S"] = "1986-05-16"; $birthdays["D"] = "1983-02-09"; echo("My birthday is: " . $birthdays["K"]); ?>

      </source>
   
  


Sort associate array

   <source lang="html4strict">

<?php

  $states = array("OH" => "Ohio", "CA" => "California", "MD" => "Maryland");
  sort($states);
  print_r($states);

?>

      </source>
   
  


Use foreach, while and list to loop through associate array

   <source lang="html4strict">

<?php $characters = array(

       array(
       "name" => "A",
       "occupation" => "A1",
       "age" => 30,
       "special power" => "A3"
       ),
       array(
       "name" => "B",
       "occupation" => "B1",
       "age" => 24,
       "special power" => "B2"
       ),
       array(
       "name" => "C",
       "occupation" => "C1",
       "age" => 45,
       "special power" => "C2"
       )
     );

foreach ($characters as $c) {

       while (list($k, $v) = each ($c)) {
               echo "$k ... $v 
"; }

} ?>

      </source>
   
  


Using both the array key and a passed-in value to modify each element value

   <source lang="html4strict">

<?php function change(&$element, $key, $mark) {

   $element = "$mark$key$mark, the $element"; 

}

$dogs = array("A" => "C", "B" => "D", "X" => "Z"); array_display($dogs, TRUE); array_walk($dogs, "change", "*"); array_display($dogs, TRUE); ?>

 </source>
   
  


Using Variable Variables to Create Associations

   <source lang="html4strict">

<?php $favorite_color = "blue"; $favorite_weapon = "gun"; $favorite_drink = "beer"; $favorite_things = array("color", "weapon", "drink"); foreach ($favorite_things as $thing) {

echo "

", $thing, " = ", ${"favorite_{$thing}"}, "

";

} ?>

 </source>