PHP/Data Structure/Associate Array

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

An array called $computers with numeric and string keys

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



An array called $vegetables with string keys

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



Argument Swapping

 
<?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"] );
}
?>



array_intersect_assoc: Computes the intersection of arrays with additional index check

<?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);
?>



array_key_exists

<?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]";
?>



array_keys: Return all the keys of an array

<?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 )
?>



Arrays Using Associative Array Notation

<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("<pre>" . $cars_var_dump . "</pre>");
?>
</body>
</html>



Array to object

 
<?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";
?>



array_values: Return all the values of an array

<?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 )
?>



Assigning and Comparing

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



Associative Arrays

 <?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];  
 ?>



Building an array of defaults

 
if ($_POST["_submit_check"]) {
    $defaults = $_POST;
} else {
    $defaults = array("delivery"  => "yes",
                      "size"      => "medium",
                      "main_dish" => array("taro","tripe"),
                      "sweet"     => "cake");
}



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

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



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"

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



Creating an associative array of shapes

 
<?php
$shapes = array("S" => "Cylinder",
                "N" => "Rectangle",
                "A" => "Sphere",
                "O" => "Sphere",
                "P" => "Rectangle");
?>



Creating Arrays

 
<?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 "<p>Pet number 1 is named "$pets[0]".</p>\n";
  print "<p>The person"s age is $person[2].</p>\n";
  print "<p>The customer"s age is {$customer["age"]}.</p>\n";
?>



Displaying one value from an array

 
<?php
$shapes = array("S" => "Cylinder",
                "N" => "Rectangle",
                "A" => "Sphere",
                "O" => "Sphere",
                "P" => "Rectangle");
print "A notepad is a {$shapes["Notepad"]}.";
?>



foreach statement is used to loop through an associative array

<?php
$emp_det = array (Name => "A",
                  Age => "2" ,
                  Code =>"8",
                  Designation => "Administrator");
foreach ($emp_det as $key=>$temp) {
   echo "$key = $temp","\n";
}
?>



key: Fetch a key from an associative array

<?php
   $capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines","Arizona" => "Phoenix");
   echo "<p>Can you name the capitals of these states?</p>";
   while($key = key($capitals)) {
      echo $key."<br />";
      next($capitals);
   }
?>



Looping Through an Associative Array with foreach

<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<br>";
}
?>
</body>
</html>



Obtaining Array Keys and Values

 
<?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); 
?>



Obtaining Array Keys with a Given Value

 
<?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("<p>Countries where %s is spoken: %s.</p>\n",
          $language,
          $spoken ? implode(", ", $spoken) : "None");
  
  $language = "Tagalog";
  $spoken = array_get_keys($language, $countries);
  
  printf("<p>Countries where %s is spoken: %s.</p>\n",
          $language,
          $spoken ? implode(", ", $spoken) : "None");
?>



One-based array index

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



print_r: output associate array

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



Reference the assiciate array element

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



Sort associate array

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



Use foreach, while and list to loop through associate array

<?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 <br/>";
        }
}
?>



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

 
<?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); 
?>



Using Variable Variables to Create Associations

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