Showing posts with label PHP Arrays. Show all posts
Showing posts with label PHP Arrays. Show all posts

28 January, 2011

Check value exists in multidimensional array

Most of the times we are playing with arrays in php. And it can be troublesome when we have to check for value in multidimensional array. I get into such a situation every often. I used to loop through the array to check for the existence of value.

So, i thought of making a function that checked for the existence of a value in a multi array. I am much happier using this function rather than looping through arrays making my time worse.

Following code simplifies checking of a value in multi-array in php.

//function to check if a values exists in multidimensional array
function in_multi($searchFor, $array) {
foreach($array as $key => $value) {
if($value == $searchFor) {
return true;
}
else {
if(is_array($value)) if(in_multi($searchFor, $value)) return true;
}
}
return false;
}
//test array
$testArr = array(
0 => array(
0 => array(
"10" => 20,
"20" => 40
),
1 => array(
"a" => 555,
"b" => 152
)
),
1 => array(
0 => 999,
1 => 2024
)
);


$isThere = in_multi(152, $testArr);
if($isThere) {
echo "Found";
}
else {
echo "Not Found";
}
?>
And we are done.

27 December, 2010

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.


Let's say we have a form "form.php" as:


File:





Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
}
$dataArr []= $rowData;
}
}

//so now you can check for the array of data as:
echo "
";
print_r($dataArr);
echo "
";

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.


Let's say we have a form "form.php" as:


File:





Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
}
$dataArr []= $rowData;
}
}

//so now you can check for the array of data as:
echo "
";
print_r($dataArr);
echo "
";

01 November, 2010

CSV to Multi-Dimensional Array in PHP

Once i needed to convert a csv file contents to a multi-dimensional array in php. Converting a csv to a multi-dimensional array
can be done by reading the file by using php's fopen function and then looping through to insert data to the array.
Following is a code snippet that is used to get csv to multi-dimensional array in php.
My csv file was in the format "name" "email_address" without any column names.

$formattedArr = array();
$filename = "test.csv";
//csv format was
//name test@this.com
//tester tester@mail.com
//sudhir sudhirconscious@gmail.com
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // Set the array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get the total keys in row
//insert data to our array
for ($i=0; $i < $count; $i++) {
$formattedArr[$key][$i] = $data[$i];
}
$key++;
}
fclose($handle); //close file handle
}
//csv to multidimensional array in php
echo "
";
print_r($formattedArr);
echo "
";
And thats it.

16 September, 2010

Create breadcrumb from array

Creating breadcrumbs can sometimes be really dificult. Breadcrumbs can be created from array in php using some simple code.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.


$id = $_GET['id'];
if ( strlen( $id ) < 1 ) $id = "home";
//this array contains page lists, with id, title and parent page named as main in here
$pages = array(
'home' => array( 'id'=>"home", 'main'=>"my_home", 'title'=>"Home",
'url'=>"bcrumb.php?id=home" ),
'members' => array( 'id'=>"users", 'main'=>"home", 'title'=>"Members",
'url'=>"bcrumb.php?id=members" ),
'sudhir' => array( 'id'=>"jack", 'main'=>"users", 'title'=>"Sudhir",
'url'=>"bcrumb.php?id=sudhir" )
);
//function to create breadcrumb from array
function crumbs( $id, $pages ) {
$bCrumbList = array();
$pageid = $id;
while(strlen($pageid) > 0) {
$bCrumbList[] = $pageid;
$pageid = $pages[ $pageid ]['main'];
}
for($i = count( $bCrumbList ) - 1; $i >= 0; $i-- ) {
$page = $pages[$bCrumbList[$i]];
if ($i > 0) {
echo( " echo( $page['url'] );
echo( "\">" );
}
echo( $page['title'] );
if ( $i > 0 ) {
echo( "
| " );
}
}
}
echo "Crumbs:" .crumbs($id, $pages);
echo "
";
echo "Page:".$id;


Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.

25 August, 2010

Unset empty elements in Array

It is quite easier to unset empty element(s) in an array in php. Following code will do the work.

//this is a test array
$testArr = array(1 => "First", 2 => "", 3 => "Third", 4 => "", 5 =>"Fifth");
//loop through the array and remove empty elements
foreach($testArr as $key => $value) {
if(empty($value)) {
unset($testArr[$key]);
}
}
//view the array with empty elements removed
print_r($testArr);
?>

14 June, 2010

Find if multi-dimensional array is empty

Checking for emptinessin quite simple using php. Following function can be used to check if a multidimensional array is empty or not.
The code loops through all the values in multi-dimensional array to check for empty values.

$food = array(
'fruits' => array('', '', ''),
'veggie' => array('', '', ''),
"test" => ""
);
//set the empty count to 0
$countEmpty = 0;
//set number of keys count to 0
$countKey = 0;
foreach($food as $key => $val) {
if(is_array($val)) {
//loop through each values inside
foreach($val as $key1 => $val1) {
$val = trim($val);
if(empty($val1)) {
//empty value-- increment the empty value count
$countEmpty++;
}
//increment the key count
$countKey++;
}
}
else {
$countKey++;
$val = trim($val);
if(empty($val)) {
$countEmpty++;
}
}
}
if($countKey == $countEmpty) {
echo "Array is empty..!";
}
else {
echo "Array contains".($countKey - $countEmpty)." value(s)";
}
echo "
";
echo "Keys:".$countKey."
";
echo "Empty:".$countEmpty;
?>

17 May, 2010

maximum value from an array

Finding maximum value from an array using php is quite simple. Following code finds the maximum value from an array.

$maxValue = $resultArr[0];
foreach($searchArr as $val) {
//check for all the values for maximum value and compare it with default value
if($val["total_points"] > $maxPoint) {
$maxPoint = $val["total_points"];
}
}
echo "Maximum value is:".$maxValue;
?>
//Similarly minimum value in an array can also be found just by changing the if condition

04 May, 2010

Sort Multi-dimensional Array By Value

A multi-dimensional array can be sorted using following code snippet.
function subval_sort($arr, $subKey, $sort) {
foreach($arr as $k => $v) {
$b[$k] = strtolower($v[$subKey]);
}
$sort($b);
foreach($b as $key => $val) {
$c[] = $arr[$key];
}
return $c;
}
$testArr = array(
0 => array("name" => "test", age => 20),
1 => array("name" => "smith", age=>30)
);
Usage: subval_sort($testArr, "name", arsort);