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;
}
}
}
}
Related
I have this array:
Array
(
[datas] => Array
(
[General] => Array
(
[0] => Array
(
[id] => logo
[size] => 10
)
)
[Rooms] => Array
(
[0] => Array
(
[id] => room_1
[size] => 8
)
[1] => Array
(
[id] => room_2
[size] => 8
)
[2] => Array
(
[id] => room_3
[size] => 8
)
)
)
)
I need to update it when I receive some info like this:
$key = 'room_3';
$toChange = '9';
So in my array, I want to change the size of room_3.
I will always edit the same element (i.e. size).
What I tried:
// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
foreach ($datas as $d) {
if (array_search($got, $d)) {
if (in_array($to_find, array_keys($d))) {
return trim($d[$to_find]);
}
}
}
}
But it does not work...
Could you please help me ?
Thanks.
function getDatas($datas, $got, $to_find) {
foreach($datas['datas'] as $key => $rows) {
foreach($rows as $number => $row) {
if($row['id'] == $got) {
// u can return new value
return $row['size'];
// or you can change it and return update array
$datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
return $datas;
}
}
}
}
function changeRoomSize (&$datas, $roomID, $newSize ){
//assuming that you have provided valid data in $datas array
foreach($datas['datas']['Rooms'] as &$room){
if($room['id'] == $roomID){
$room['size'] = $newSize;
break;//you can add break to stop looping after the room size is changed
}
}
}
//--- > define here your array with data
//and then call this function
changeRoomSize($data,"room_3",9);
//print the results
var_dump($data);
It's a 3-dimensional array, if you want to change the value, do like this:
$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
if ($v2['id'] == $key)) {
$rooms[$k1][$k2]['size'] = $toChange;
}
}
return $rooms;
}
print_r($array);
I'm having a hard time looping in a multidimensional array. I'm not an expert of some sort when it comes to PHP. What I want to happen is to search for a certain field. If it hits the right field, then it will grab the data and store in a variable and if it does not hit the right field, it will continue to search for the right field.
Here's the array
[111] => Array
(
[tag] => B:VALUE
[type] => close
[level] => 7
)
[112] => Array
(
[tag] => B:KEYVALUEOFINTHEALTHAGENCYD9J3W_PIR
[type] => close
[level] => 6
)
[113] => Array
(
[tag] => A:AGENCIES
[type] => close
[level] => 5
)
[114] => Array
(
[tag] => A:TOKEN
[type] => complete
[level] => 5
[value] => vy8BMS8nDIFdQWRTb6wyNDGGUMgBzHtOXU6mHqZgdxhRAbi0qkwluK9pjt03OQyf
)
[115] => Array
(
[tag] => LOGINCAREGIVERPORTALRESULT
[type] => close
[level] => 4
)
[116] => Array
(
[tag] => LOGINCAREGIVERPORTALRESPONSE
[type] => close
[level] => 3
)
[117] => Array
(
[tag] => S:BODY
[type] => close
[level] => 2
)
[118] => Array
(
[tag] => S:ENVELOPE
[type] => close
[level] => 1
)
and here's my code and I would like to apologize first for not being able to complete it. :D ......i have totally no idea on what to place.....and searching is making me more confuse...sorry....
here's the code
$last = count($vals) - 1;
foreach ($vals as $i => $row) {
if (!$vals == '114') {
next
}
else {
$sessiontoken = <------store the value here
}
}
Try the following:
foreach ($values as $key => $value){
if ($key == '114') {
if($value['tag']==='A:TOKEN')
$sessiontoken = $value['value'];
}
}
Your actual question suggests you are looking to always return key '114'. In that case, you don't need a loop at all, just reference that key:
$sessiontoken = $vals['114']['value'];
However, what I think you actually want is to find whichever element has a 'tag' of 'A:TOKEN', which would look like this:
foreach ($vals as $i => $row) {
// Here, $row is one item from the $vals array
// You don't want to think about $vals in the condition, just $row
if ( $row['tag'] != 'A:TOKEN' ) {
continue; // there's no "next" keyword in PHP
}
else {
$sessiontoken = $row['value'];
}
}
I'd probably swap the if around like this, though:
foreach ($vals as $i => $row) {
if ( $row['tag'] == 'A:TOKEN' ) { // Positive tests are easier to read
$sessiontoken = $row['value'];
}
// you can look for other tags at the same time with elseif ( ... )
else {
continue; // only if none of your conditions are met
}
// if there's nothing after the end of the else,
// you don't need the continue at all
}
Assuming you want to find the the session token which is contained in only one of your results. Do the following:
foreach ($vals as $i => $array_value){
if (isset($array_value[$i]['value']) {
$sessiontoken = $array_value[$i]['value'];
break; // stop looping after it is found
}
}
This one liner right here should be fixed:
if (!$vals == '114') {
Assuming that you want to store the session if you found the item you want at position 114, you should do something like this. I'm under the assumption that you have an array at position 114, and then you have keys that are pointing to a value? It seems like from your description that each key is actually an array that points to a value? Assuming that it's a regular key-value pair, here's something you can try:
foreach ($vals as $key=>$value)
{
if ($key !== '114')
{
continue;
} else {
// check if value exists
if (!empty($value['value'])
{
$sessionToken = $value['value'];
}
}
}
If it's not a key-value pair, then you need to adjust it to something like:
foreach ($vals as $key=>$value)
{
if ($key !== '114')
{
continue;
} else {
foreach ($value as $keyArray => $val)
{
if ($keyArray == 'value')
{
$sessionToken = $value['value'];
}
}
}
}
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]);
}
}
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.
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";
}