01c07-1.php

来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 54 行

PHP
54
字号
<?php// A function to display a multidimensional array as text columns.  // $spacing should be set to the number of spaces you wish between columnsfunction display_array($arr, $spacing) {	// We need to determine the maximum width of each column in the array	$widths = array();		// Loop through all rows	foreach ($arr as $row) {		// Examine each column		foreach ($row as $key => $col) {			// If this entry is wider than others in the column, store it			if (!isset($widths[$key]) || (strlen($col) > $widths[$key])) {				$widths[$key] = strlen($col);			}		}	}		// Now that we have the maximum widths, we can loop through the	//  array, printing out each row	echo '<pre>';	foreach ($arr as $row) {		$count = 0;		foreach ($row as $key => $col) {			// If this is not the first one, add the spacing:			if ($count++) {				echo str_repeat(' ', $spacing);			}						// Echo out the column, padded appropriately			echo str_pad($col, $widths[$key]);		}		echo "\n";	}}$test_array = array(	array('NAME', 'CITY', 'STATE', 'PHONE', 'EMAIL'),	array('Bob Smith', 'Baltimore', 'MD', '410-555-1212', 'bs@nomail.com'),	array('Jane Doe', 'Gary', 'IN', '999-555-7136', 'jane@tarzan.com'),	array('William Fences', 'Redmond', 'WA', 			'123-555-4567', 'opening@fencesinc.com'),	array('Steven Works', 'Cupertino', 'CA', 			'023-555-4991', 'works@orange.com')	);// Display the array, echos:// NAME            CITY          STATE  PHONE         EMAIL// Bob Smith       Baltimore     MD     410-555-1212  bsmith@nomail.com// Jane Doe        Indianapolis  IN     999-555-7136  jane@tarzan.com// William Fences  Redmond       WA     123-555-4567  opening@fencesinc.com// Steven Works    Cupertino     CA     023-555-4991  works@orange.com     display_array($test_array, 3);?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?