PHP/Data Structure/Multidimensional Array

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

Accessing multidimensional array elements

 
<?
$meals = array("breakfast" => array("A","C"),
               "lunch"     => array("B", "E"),
               "snack"     => array("C","F"));
$lunches = array( array("Chicken","Eggplant","Rice"),
                  array("Eggplant","Tofu"));
$flavors = array("Japanese" => array("hot" => "1",
                                     "salty" => "2"),
                 "Chinese"  => array("hot" => "3",
                                     "pepper-salty" => "4"));
print $meals["lunch"][1];            
print $meals["snack"][0];            
print $lunches[0][0];                
print $lunches[2][1];                
print $flavors["Japanese"]["salty"]  
print $flavors["Chinese"]["hot"];    
?>



Creating a Multidimensional Array

 
<?php
    $myarray = array("mykey"=> "myvalue","key2"=> array(1, 2, 3, 4));
    $sub_array[] = 1;
    $sub_array[] = 2;
    $sub_array[] = 3;
    $sub_array[] = 4;
    $example["mykey"] = "myvalue";
    $example["key2"]  = $sub_array;
    $anotherarray["mykey"] = "myvalue";
    $anotherarray["key2"][] = 1;
    $anotherarray["key2"][] = 2;
    $anotherarray["key2"][] = 3;
    $anotherarray["key2"][] = 4;
?>



Creating Multidimensional Arrays

 
<?php
  $customers= array(
        array("first" => "Bill", "last" => "Jones",
              "age" => 24, "state" => "CA"),
        array("first" => "Joyce", "last" => "Johnson",
              "age" => 21, "state" => "TX"),
      );
      
  $pet_breeds= array(
            "dogs" => array("P", "T", "D"),
            "birds" => array("P", "C"),
            "fish" => array("G", "T", "C", "A")
      );
      
  printf("<p>The name of the second customer is %s %s.</p>\n",
          $customers[1]["first"], $customers[1]["last"]);
          
  printf("<p>%s and %s</p>", 
          $pet_breeds["dogs"][0], $pet_breeds["birds"][1]);
?>



Defining a Multidimensional Array

<html>
<head>
<title>Defining a Multidimensional Array</title>
</head>
<body>
<?php
$characters = array (
                array ( name=>"name 1",
                        occupation=>"developer",
                        age=>30,
                        specialty=>"Java" ),
                array ( name=>"name 2",
                        occupation=>"Programmer",
                        age=>24,
                        specialty=>"C++" ),
                array ( name=>"name 3",
                        occupation=>"designer",
                        age=>63,
                        specialty=>"Javascript" )
);
print $characters[0][occupation];
?>
</body>
</html>



Displaying a multidimensional array

 
<?php
$objects=array("A" =>    array("Shape"    => "Cylinder",
                                      "Color"    => "Red",
                                      "Material" => "Metal"),
               "B" =>    array("Shape"    => "Rectangle",
                                      "Color"    => "White",
                                      "Material" => "Paper"),
               "C" =>       array("Shape"    => "Sphere",
                                      "Color"    => "Red",
                                      "Material" => "Fruit"),
               "D" =>      array("Shape"    => "Sphere",
                                      "Color"    => "Orange",
                                      "Material" => "Fruit"),
               "E" =>  array("Shape"    => "Rectangle",
                                      "Color"    => "Yellow",
                                      "Material" => "Paper"));
echo $objects["Soda can"]["Shape"];
foreach ($objects as $obj_key => $obj)
{
    echo "$obj_key:<br>";
    while (list ($key,$value)=each ($obj))
    {
        echo "$key = $value ";
    }
    echo "<br />";
}
?>



Displaying a Multidimensional Array using For each

<?php
  $emp_det = array (array (Name=>"a", Code=> "8", Hobby=> "A"),
                    array (Name=>"b", Code=> "8", Hobby=> "B"),
                    array (Name=>"c", Code=> "1", Hobby=> "C"),
                    array (Name=>"d", Code=> "3", Hobby=> "D"),
  );
  foreach ($emp_det as $tempone) {
    foreach ($tempone as $key=>$temptwo) {
      echo "$key: $temptwo", "\n";
    }
    echo "\n";
  }
?>



Displaying Multidimensional Arrays

 
<?php
function display_array($arr, $spacing) {
    $widths = array();
    foreach ($arr as $row) {
        foreach ($row as $key => $col) {
            if (!isset($widths[$key]) || (strlen($col) > $widths[$key])) {
                $widths[$key] = strlen($col);
            }
        }
    }
    echo "<pre>";
    foreach ($arr as $row) {
        $count = 0;
        foreach ($row as $key => $col) {
            if ($count++) {
                echo str_repeat(" ", $spacing);
            }
            echo str_pad($col, $widths[$key]);
        }
        echo "\n";
    }
}
$test_array = array(
    array("A", "B", "C", "D", "E"),
    array("a", "b", "c", "d", "e"),
    );
display_array($test_array, 3);
?>



Find the Maximum Value in a Multidimensional Array

 
<?php
function recursive_array_max($a) {
    foreach ($a as $value) {
        if (is_array($value)) {
            $value = recursive_array_max($value);
        }
        if (!(isset($max))) {
            $max = $value;
        } else {
            $max = $value > $max ? $value : $max;
        }
    }
    return $max;
}
$dimensional = array(
    7,
    array(3, 5),
    array(5, 4, 7, array(3, 4, 6), 6),
    14,
    2,
    array(5, 4, 3)
    );
$max = recursive_array_max($dimensional);
echo "<p>The maximum value was: {$max}</p>";
?>



Generating fixed-width field data records without

 
<?php
$books = array( array("A","S", 1927),
                array("T","L",1971),
                array("T","W",1979) );
foreach ($books as $book) {
    $title  = str_pad(substr($book[0], 0, 25), 25, ".");
    $author = str_pad(substr($book[1], 0, 15), 15, ".");
    $year   = str_pad(substr($book[2], 0, 4), 4, ".");
    print "$title$author$year\n";
}
?>



Looping Through a Multidimensional Array

<html>
<head>
<title>Looping Through a Multidimensional Array</title>
</head>
<body>
<?php
$characters = array (
                array ( name=>"name 1",
                        occupation=>"developer",
                        age=>30,
                        specialty=>"Java" ),
                array ( name=>"name 2",
                        occupation=>"Programmer",
                        age=>24,
                        specialty=>"C++" ),
                array ( name=>"name 3",
                        occupation=>"designer",
                        age=>63,
                        specialty=>"Javascript" )
);
foreach ( $characters as $val ){
    foreach ( $val as $key=>$final_val ){
        print "$key: $final_val<br>";
    }
    print "<br>";
}
?>
</body>
</html>



Manipulating multidimensional arrays

 
<?
$prices["dinner"]["A"] = 12.50;
$prices["lunch"]["B"] = 4.95;
$prices["dinner"]["C"] = 8.95;
$prices["dinner"]["total"] = $prices["dinner"]["A"] +
                             $prices["dinner"]["B"];
$specials[0][0] = "aa";
$specials[0][1] = "bb";
$specials[0][2] = "cc";
$specials[1][0] = "dd";
$specials[1][1] = "ee";
$specials[1][] = "Peanut Salad";
?>



Multidimensional array element value interpolation

 
<?
$specials = array( array("A", "A", "B"),
                   array("C","W", "P") );
for ($i = 0, $num_specials = count($specials); $i < $num_specials; $i++) {
    for ($m = 0, $num_sub = count($specials[$i]); $m < $num_sub; $m++) {
        print "Element [$i][$m] is {$specials[$i][$m]}\n";
    }
}
?>



Reference element in multidimensional Arrays

<?php
  $emp_det = array (array (Name=>"a", Code=> "8", Hobby=> "A"),
                    array (Name=>"b", Code=> "8", Hobby=> "B"),
                    array (Name=>"c", Code=> "1", Hobby=> "C"),
                    array (Name=>"d", Code=> "3", Hobby=> "D"),
  );
  echo $emp_det [0] [Hobby];
?>



Sorting Multidimensional Arrays

 
<?php 
$data = array( 
    array("country"=>"Spain", "language"=>"Spanish", "visitors"=>1289), 
    array("country"=>"France", "language"=>"French", "visitors"=>984), 
    array("country"=>"Argentina", "language"=>"Spanish", "visitors"=>812)
); 
printf("<pre>%s</pre>\n", var_export($data, TRUE)); 
$cols = array(); 
foreach($data as $row) { 
    foreach($row as $key => $value) { 
        if( !isset($cols[$key]) ) 
            $cols[$key] = array(); 
        $cols[$key][] = $value; 
    } 
} 
$data = $cols; 
array_multisort($data["language"], $data["country"], $data["visitors"]); 
printf("<pre>%s</pre>\n", var_export($data, TRUE)); 
?>