Removing an item from a session associative arrays in php - php

I am really stuck with this. It is an array within an array such as:
Array ( [0] => Array ( [item] => product1 [unitprice] => 15 [quantity] => 1 ) [1] => Array ( [item] => product2 [unitprice] => 15 [quantity] => 1 ) )
I have tried to remove a specific item using:
$pid=$_GET['id']; (where id = product1)
$delete=array_splice($_SESSION['cart'], array_search($id, $_SESSION['cart']), 1);
unset($delete);
print_r($_SESSION['cart']);
This seems to randomly remove items. Any help would be greatly appreciated

<?php
function searchForItem($id, $array) {
foreach ($array as $key => $val) {
if ($val['item'] === $id) {
return $key;
}
}
return null;
}
$pid=$_GET['id'];
$id = searchForItem($pid, $_SESSION['cart']);
unset($_SESSION['cart'][$id]);
?>

you mean:
foreach($_SESSION['cart'] as $index => $v) {
if(($key = array_search($pid, $v)) !== false) {
unset($_SESSION['cart'][$index]);
}
}

Related

Removing elements from multidimensional array

Hi I am having a few issues unsetting an entire row from a multidimensional array. I have an array that takes the following format
Array
(
[0] => Array
(
[ID] => 10000
[Date] => 21/11/2013
[Total] => 10
)
[1] => Array
(
[ID] => 10001
[Date] => 21/12/2013
[Total] => abc
)
...
)
I am looping this array to check that the Total contains only numbers or a period.
foreach($this->csvData as &$item) {
foreach($item as $key => $value) {
if($key === 'Total') {
$res = preg_replace("/[^0-9.]/", "", $item[$key] );
if(strlen($res) == 0) {
unset($item[$key]);
} else {
$item[$key] = $res;
}
}
}
}
So you can see from my array, the second element Total contains abc, therefore the whole element it is in should be removed. At the moment, with what I have, I am getting only that element removed
[1] => Array
(
[ID] => 10001
[Date] => 21/12/2013
)
How can I remove the whole element?
Thanks
Try this:
//Add key for outer array (no longer need to pass-by-reference)
foreach($this->csvData as $dataKey => $item) {
foreach($item as $key => $value) {
if($key === 'Total') {
$res = preg_replace("/[^0-9.]/", "", $item[$key] );
if(strlen($res) == 0) {
// Unset the key for this item in the outer array
unset($this->csvData[$dataKey]);
} else {
$item[$key] = $res;
}
}
}
}

PHP Flipping multidimentional array doesn't work

I come up with this code:
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
array_flip($array);
}
return $array;
}
but it doesnt work.
It returns unchanged array.
here is the array data sample:
Array
(
[0] => Array
(
[0] => Array
(
[zip] => 02135
[hispanic_percent] => 7.4
[white_percent] => 73.1
[black_percent] => 4.2
[native_american_percent] => 0
)
)
[1] => Array
(
[0] => Array
(
[zip] => 02135
[school_number] => 1
[school_name] => ANOTHER COURSE TO COLLEGE
[school_address] => 20 WARREN STREET BRIGHTON MA 02135
[contact_number] => 617-635-8865
[start_grade] => 9TH GRADE
[reduced_lunch_students_count] => 8
[reduced_lunch_students_percent] => 120
[free_or_reduced_lunch_students_count] => 53
[free_or_reduced_lunch_students_percent] => 0
)
)
)
You have to reassign the return value of the array_flip function to your $array variable in order to work.
You need to modify your function to work it correctly. Reassign the values after array_flip
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
$array = array_flip($array);
}
return $array;
}
Hope this helps :)

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Find value and key in multidimensional array

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.
Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}
You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}
First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.
I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"
This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>
Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");
function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

Multi-Dimensional Arrays

I have an array structure like this, which I'm able to print out just fine:
Array
(
[0] => Array
(
[title] => blah
[author] => Bob
[link] => randomlink
)
[1] => Array
(
[title] => random
[author] => George
[link] => randomlink
)
[2] => Array
(
[title] => blah
[author] => Bob
[link] => randomlink
)
)
Basically, I want to be able to print out only the information in the array that's related to the 'author' 'Bob'. As you can see, he has two items in there. When I print out the array, it should only show the 0 and 2 array since those are the only ones that contain the 'author' which is 'Bob'. Any ideas?
foreach ($array as $a)
{
if($a['author'] === 'Bob') {
echo $a['title'];
echo $a['author'];
echo $a['link'];
}
}
foreach($arr as $item)
{
if($item['author'] != 'Bob')
{
continue;
}
// print out Bob's stuff
}
This is the code:
foreach($array as $subarray)
{
if(strcasecmp($subarray['author'],'Bob') === 0)
print_r($subarray);
}
Simply foreach
foreach ($array as $item) {
if ($item['author']) {
// Do something with $item
}
}
ok ! try this :
for($i=0;$i<count($array);$i++){
if($array[$i]['author'] == 'bob'){
echo $array[$i]['title']." > ".$array[$i]['author']." > ".$array[$i]['link']."\r\n<br>";
}
}
...

Categories