Jump to content

Remove item from multidimensional array?


John_A

Recommended Posts

Lets sat I have a multidimensional array. call it $my_array....

 

Print_r($my_array) gives: -

 

Array
(
    [parent] => Array
        (
            [child] => Array
                (
                    [0] => Array
                        (
                            [itemID] => 3
                            [name] => This Item
                            [lowlimit] => 50
                            [highlimit] => 0
                        )

                    [1] => Array
                        (
                            [itemID] => 6
                            [name] => That Item
                            [lowlimit] => 50
                            [highlimit] => 0
                        )

                )

        )
)

 

It's the child items I want to deal with. It won't always have both items, it may have only 1 or more. I want to look for any child item who's [name] key includes the string "This", and if found remove that whole child item (in this case $my_array -> parent -> child -> 0) and then fix the indexing again so they start at 0 and increment OK.

 

The trouble is, I don't know where to start? Any help much appreciated!

Link to comment
https://forums.phpfreaks.com/topic/202475-remove-item-from-multidimensional-array/
Share on other sites

John_A,

 

    I played around with your request and came up with the following...

 

    Looks like it produces the output you want.

 

    Let us know.

 

Scot L. Diddle, Richmond VA

 

 


<?php

Header("Cache-control: private, no-cache");
Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
Header("Pragma: no-cache");

$my_array = Array(    'parent' => Array  (

		'child' => Array  (

					0 => Array (

						 'itemID' => 3,
						 'name' => 'This Item',
						 'lowlimit' => 50,
						 'highlimit' => 0
                        ),

                    1 => Array (

                   		 'itemID' => 6,
                   		 'name' => 'That Item',
                   		 'lowlimit' => 50,
                   		 'highlimit' => 0,
                   		 )

                   		)
                   	)
               );

               $display = FALSE;

               if ($display) {

                   require_once('includes/debugFunctions.php');

                   printArray($my_array, '$my_array', __FILE__, __LINE__);

                   exit;

//	                   Name :: $my_array :: should look like the following:
//
//
//							Array
//							(
//							    [parent] => Array
//							        (
//							            [child] => Array
//							                (
//							                    [0] => Array
//							                        (
//							                            [itemID] => 3
//							                            [name] => This Item
//							                            [lowlimit] => 50
//							                            [highlimit] => 0
//							                        )
//
//							                    [1] => Array
//							                        (
//							                            [itemID] => 6
//							                            [name] => That Item
//							                            [lowlimit] => 50
//							                            [highlimit] => 0
//							                        )
//
//							                )
//
//							        )
//
//							)
//


               }


if (is_array($my_array)) {

   foreach($my_array as $parentIDX => $currentChild) {

   		if (is_array($currentChild)) {

   			foreach ($currentChild as $childIDX => $arrayItem) {

   				$display = FALSE;

   				if ($display) {

   				    require_once('includes/debugFunctions.php');

   				    printArray($arrayItem, '$arrayItem', __FILE__, __LINE__);

//	   				    Name :: $arrayItem :: should look like the following:
//
//							Array
//							(
//							    [0] => Array
//							        (
//							            [itemID] => 3
//							            [name] => This Item
//							            [lowlimit] => 50
//							            [highlimit] => 0
//							        )
//
//							    [1] => Array
//							        (
//							            [itemID] => 6
//							            [name] => That Item
//							            [lowlimit] => 50
//							            [highlimit] => 0
//							        )
//
//							)

   				}

   				if (is_array($arrayItem)) {

   					foreach($arrayItem as $itemIDX => $deleteCandidate) {

   						$searchItem = $deleteCandidate['name'];

	   					$contains_This = stristr($searchItem,'This');

						if ($contains_This) {

							$arrayItemToDelete = array($my_array[$parentIDX][$childIDX][$itemIDX]);

							unset($my_array[$parentIDX][$childIDX][$itemIDX]);

							// Re-sequence the lowest-level array key vakues...
							$my_array[$parentIDX][$childIDX] = array_values($my_array[$parentIDX][$childIDX]);

						}

   					}

   				}
   				else {
   					echo "Selected variable : \"\$arrayItem\" ( value: " . $arrayItem . " ) is not an array ! ";
   				}

   			}

   			$display = FALSE;

   			if ($display) {

   			    require_once('includes/debugFunctions.php');

   			    printArray($my_array, '$my_array', __FILE__, __LINE__);
   			    
//	   			    Name :: $my_array :: should look like this:
//
// 
//						Array
//						(
//						    [parent] => Array
//						        (
//						            [child] => Array
//						                (
//						                    [0] => Array
//						                        (
//						                            [itemID] => 6
//						                            [name] => That Item
//						                            [lowlimit] => 50
//						                            [highlimit] => 0
//						                        )
//						
//						                )
//						
//						        )
//						
//						)



   			}

   		}
   		else {
   			echo "Selected variable : \"\$currentChild\" ( value: " . $currentChild . " ) is not an array ! ";
   		}

   }

}
else {

	echo "Selected variable : \"\$my_array\" ( value: " . $my_array . " ) is not an array ! ";
}

?>






 

For giggles, here is my dbug code:

 


<?php

    #-- Assignment : List arbitary number of name in an HTML table
    
    function listNames() {
	GLOBAL $table;
	$table = "<table border=\"1\"> \n";
	if (func_num_args() > 0) {
		$numOfArgs = func_num_args();

		for ($i=0; $i < $numOfArgs; $i++) {

			$table .= "  <tr> \n";
			$table .= "    <td>    \n";
			$table .= func_get_arg($i);
			$table .= "      </td> \n";
			$table .= "  </tr> \n";
		}
	}
	else {
		echo "No Args Passed" . " <br /> \n";
	}
	$table .= "</table> \n";
	return $table;
}

   #-- END Assignment : List arbitary number of name in an HTML table
   # -- printArray : List members in a array -- #
   
function printArray($arrayName, $name = false, $file=NULL, $line=NULL) {

	if ($file == NULL) {
		$file = '*** Not Specified ***';
	}

	if ($line == NULL) {
		$line = '*** Not Specified ***';
	}

	if ($name || $name === 0)  {
		echo "Name :: $name" . " :: Reporting from line :: " . $line .  " :: in program :: " . $file . " ::<br /> \n";
	}
	if (!is_array($arrayName)) {

		$saveArray = $arrayName;

		$arrayName = 'Not An Array';

		$possibleString = TRUE;
	}
	if (empty($arrayName)) {
		$arrayName = 'Array Contains No Data';
	}


	echo "<font color=\"#205E75\"> \n";
	echo "<pre> \n";

		print_r($arrayName);

	echo "</pre> \n";

	echo "</font> \n";

	if ($possibleString == TRUE) {

		$string = $saveArray;

		if ($string == NULL) {

			$string = 'Null String';
		}

		echo "<font color=\"#205E75\"> \n";
		echo " <br /> <br /> \n";
		echo '$array as string: ' . $string  . "<br /> <br /> \n";
		echo " <br /> <br /> \n";
		echo "</font> \n";

	}
}

function printArrayVarDump($arrayName, $name = false, $file=NULL, $line=NULL) {

	if ($file == NULL) {
		$file = '*** Not Specified ***';
	}

	if ($line == NULL) {
		$line = '*** Not Specified ***';
	}


	if ($name)  {
		echo "Name :: $name" . " :: Reporting from line :: " . $line .  " :: in program :: " . $file . " ::<br /> \n";
	}
	echo "<pre> \n";
		var_dump($arrayName);
	echo "</pre> \n";

	if ($possibleString == TRUE) {

		$string = $arrayName;

		if ($string == NULL) {

			$string = 'Null String';
		}

		echo '$array as string: ' . $string  . "<br /> <br /> \n";

	}
	// echo " <br /> <br /> \n";
}

function arrayPrint($arrayName, $name = false) {
	printArray($arrayName, $name = false);
}

?>

    I played around with your request and came up with the following...

 

    Looks like it produces the output you want.

 

    Let us know.

 

That's excellent Scot, thanks a lot. It does indeed do exactly what I wanted :)

 

Just a few questions:-

 

1) The "parent" and "child" labels I gave in my example are known values, which I admit wasn't clear by my choice of using "parent" and "child"! Would it be more efficient to use these when looking for the keys / values, rather than checking every possibiilty (it's part of a fairly large array).

 

2) Is it easily changed to look for "This" or "That" (or an array of strings to check for)?

John_A,

 

    Actually, my original post did not handle more than one  name["This"]    in your children.

 

  I corrected the error in the re-posted code.

 

  Your choices of 'parent' and 'child' are irrelevent to how this script works, because we extract whatever index_names we use via the 'as $someIDX => $someArrayValue'  schema.

 

  It only took a little checking to detetermine whether or not the search value(s) of interest  is a string or an array.  If it is a string, we convert it to an array so that the new "foreach($my_search as $my_searchIDX => $my_searchItem) {" will work.

 

  Also note, that in order to handle changing values, I converted the orignial script to include a function call.

 

  Hope this helps.

 

Scot L. Diddle, Richmond VA

 


<?php

Header("Cache-control: private, no-cache");
Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
Header("Pragma: no-cache");

$some_array = Array(    'parent' => Array  (

		'child' => Array  (

					0 => Array (

						 'itemID' => 3,
						 'name' => 'This Item',
						 'lowlimit' => 50,
						 'highlimit' => 0
                        ),

                    1 => Array (

                   		 'itemID' => 6,
                   		 'name' => 'That Item',
                   		 'lowlimit' => 50,
                   		 'highlimit' => 0,
                   		 ),

                    2 => Array (

                   		 'itemID' => 9,
                   		 'name' => 'This Other Item',
                   		 'lowlimit' => 50,
                   		 'highlimit' => 0,
                   		 ),


                    3 => Array (

                   		 'itemID' => 9,
                   		 'name' => 'Some Other Item',
                   		 'lowlimit' => 50,
                   		 'highlimit' => 0,
                   		 ),

                   		)
                   	)


               );

               $display = FALSE;

               if ($display) {

                   require_once('includes/debugFunctions.php');

                   printArray($my_array, '$my_array', __FILE__, __LINE__);

                   exit;

//	                   Name :: $my_array :: should look like the following:
//
//
//							Array
//							(
//							    [parent] => Array
//							        (
//							            [child] => Array
//							                (
//							                    [0] => Array
//							                        (
//							                            [itemID] => 3
//							                            [name] => This Item
//							                            [lowlimit] => 50
//							                            [highlimit] => 0
//							                        )
//
//							                    [1] => Array
//							                        (
//							                            [itemID] => 6
//							                            [name] => That Item
//							                            [lowlimit] => 50
//							                            [highlimit] => 0
//							                        )
//
//							                )
//
//							        )
//
//							)
//


               }

$searchIndexName = 'name';

// $search          = 'This';

$search          = array('This', 'Some');

if (!is_array($search)) {

	$search = array($search);
}

$result = parseArray($some_array, $searchIndexName, $search);

$display = TRUE;

if ($display) {

    require_once($toodles . 'includes/debugFunctions.php');
    echo "</script> \n";
    printArray($result, '$result', __FILE__, __LINE__);

}

//	   			    Name :: $result :: should look like this:
//
//
//						Array
//						(
//						    [parent] => Array
//						        (
//						            [child] => Array
//						                (
//						                    [0] => Array
//						                        (
//						                            [itemID] => 6
//						                            [name] => That Item
//						                            [lowlimit] => 50
//						                            [highlimit] => 0
//						                        )
//
//						                )
//
//						        )
//
//						)
//
//
//                 }

function parseArray($array, $searchIndexName, $search) {

	$my_array = $array;

	$my_search_indexName = $searchIndexName;

	$my_search    	     = $search;

		foreach($my_search as $my_searchIDX => $my_searchItem) {

		if (is_array($my_array)) {

		   foreach($my_array as $parentIDX => $currentChild) {

		   		if (is_array($currentChild)) {

		   			foreach ($currentChild as $childIDX => $arrayItem) {

		   				$display = FALSE;

		   				if ($display) {

		   				    require_once('includes/debugFunctions.php');

		   				    printArray($arrayItem, '$arrayItem', __FILE__, __LINE__);

	//	   				    Name :: $arrayItem :: should look like the following:
	//
	//							Array
	//							(
	//							    [0] => Array
	//							        (
	//							            [itemID] => 3
	//							            [name] => This Item
	//							            [lowlimit] => 50
	//							            [highlimit] => 0
	//							        )
	//
	//							    [1] => Array
	//							        (
	//							            [itemID] => 6
	//							            [name] => That Item
	//							            [lowlimit] => 50
	//							            [highlimit] => 0
	//							        )
	//
	//							)

		   				}

		   				if (is_array($arrayItem)) {

		   					foreach($arrayItem as $itemIDX => $deleteCandidate) {

		   						$searchItem = $deleteCandidate[$my_search_indexName];

			   					$contains_This = stristr($searchItem,$my_searchItem);

								if ($contains_This) {

									$arrayItemToDelete = array($my_array[$parentIDX][$childIDX][$itemIDX]);

									// Re-sequence the lowest-level array key vakues...
									// $my_array[$parentIDX][$childIDX] = array_values($my_array[$parentIDX][$childIDX]);

									unset($my_array[$parentIDX][$childIDX][$itemIDX]);

								}

		   					}

		   					$my_array[$parentIDX][$childIDX] = array_values($my_array[$parentIDX][$childIDX]);

		   				}
		   				else {
		   					echo "Selected variable : \"\$arrayItem\" ( value: " . $arrayItem . " ) is not an array ! ";
		   				}

		   			}

		   		}
		   		else {
		   			echo "Selected variable : \"\$currentChild\" ( value: " . $currentChild . " ) is not an array ! ";
		   		}

		   }



		}
		else {

			echo "Selected variable : \"\$my_array\" ( value: " . $my_array . " ) is not an array ! ";
		}

	}

  return $my_array;

}

?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.