I have a session that looks like this:
array(3) {
["counter"]=>
int(0)
["currentItem"]=>
string(1) "2"
["addedToCart"]=>
array(12) {
[0]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(2) "21"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
[1]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(1) "7"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
[2]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(2) "22"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
}
}
Now, from $_SESSION['addedToCart] I would like to remove arrays if they meet to certain conditions. I have tried the following.
foreach ($_SESSION["addedToCart"] as $arr) {
if ($arr["stoeltjes"] == $stoeltje && $arr['film_id'] == $id) {
unset($arr);
}
}
This doesn't seem to work, it doesn't remove anything, I did a var_dump to check if the variables $stoeltje and $id were fine and they were fine so that cant be the problem.
Am I able to use unset in this kind of situation?
foreach ($_SESSION["addedToCart"] as &$arr)
& turns your variable into a reference instead of a copy. Normally this would be sufficient. unset() only works on data within the current scope (so your foreach loop) leaving the original unchanged (See unset() for details).
Instead you can do:
foreach ($_SESSION["addedToCart"] as $key => $val)
{
if ($val["stoeltjes"] == $stoeltje && $val['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
Even if the suggested way with the reference should work normally, here's an example without it:
foreach ($_SESSION["addedToCart"] as $key => $arr) {
if ($arr["stoeltjes"] == $stoeltje && $arr['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
It doesn't work, because foreach is working on a copy, therefore $arr is just a copy of each element in the main table.
from php.net:
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
Try this:
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => &$value) {
if ($value == 2)
{
unset($arr[$key]);
}
}
print_r($arr);
remove_array_key("film_id", $array);
function remove_array_key($key, &$array)
{
$result = array_key_exists($key, $array);
if ($result) {
unset($array[$key]);
return $array;
}
foreach ($array as &$v) {
if (is_array($v)) {
$result = remove_array_key($key, $v);
}
if (is_array($result)) {
unset($v[$key]);
return $array;
}
}
return false;
}
Link to Github Explanation
Related
Output of var_dump($arr)
array(4) {
[0]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(2) "4
"
}
[1]=>
array(4) {
[0]=>
string(1) "5"
[1]=>
string(1) "6"
[2]=>
string(1) "7"
[3]=>
string(2) "8
"
}
[2]=>
array(4) {
[0]=>
string(1) "9"
[1]=>
string(2) "10"
[2]=>
string(2) "11"
[3]=>
string(3) "12
"
}
[3]=>
array(4) {
[0]=>
string(2) "13"
[1]=>
string(2) "14"
[2]=>
string(2) "15"
[3]=>
string(2) "16"
}
}
i Want to remove \n in $arr array.
I tried to use array_walk($arr,'intval'); but it did not work, because it is multiple dimensional array. What's the solution?
Is there any inbuilt PHP function? Or I need to use loops and remove it?
P.S: I am a newbie, try not to get too technical.
You can just do
array_walk_recursive($arr, function(&$v) { $v = trim($v); });
You cannot use trim directly as the callback, because it doesn't accept arguments by reference, so you have to wrap it in a callback that does.
Demo https://eval.in/904410
You can achieve this via loop and array_map()
$arr = array(
array("1", "2", "3", "4\n"),
array("5", "6", "7", "8\n"),
array("9", "10", "11", "12\n"),
array("13", "14", "15", "16\n"),
);
// result array
$result = [];
// Loop thru array
foreach ($arr as $value) {
// Map thru $value with trim to remove \n then push to result
$result[] = array_map('trim', $value);
}
// Output
echo('<pre>');
print_r($result);
There are alternatives, but recursively looping through your array gives you flexibility about what to remove, not only newlines:
function removeNewline($array) {
$result = array();
foreach ($array as $key => $value) {
// If the array value is an array itself, call the function recursively
if (is_array($value)) {
$result[$key] = removeNewline($value);
} else {
// Only remove newlines from strings
if (is_string($value)) {
$result[$key] = preg_replace('/\s+/', '', $value);
} else {
$result[$key] = $value;
}
}
return $result;
}
This question already has answers here:
Merging and group two arrays containing objects based on one identifying column value
(4 answers)
Closed 5 months ago.
After I merged two arrays like this array_merge($array1, $array2);, it becomes like this:
array(10) {
[0]=>
object(stdClass) (2) {
["id"]=>
string(1) "1"
["text"]=>
string(5) "one"
}
[1]=>
object(stdClass) (2) {
["id"]=>
string(1) "2"
["text"]=>
string(8) "two"
}
[2]=>
object(stdClass) (2) {
["id"]=>
string(1) "3"
["text"]=>
string(4) "three"
}
[3]=>
object(stdClass) (2) {
["id"]=>
string(1) "4"
["text"]=>
string(8) "four"
}
[4]=>
object(stdClass) (2) {
["id"]=>
string(1) "5"
["text"]=>
string(3) "five"
}
[5]=>
object(stdClass) (2) {
["id"]=>
string(1) "1"
["unit"]=>
string(1) "0"
}
[6]=>
object(stdClass) (2) {
["id"]=>
string(1) "2"
["unit"]=>
int(0)
}
[7]=>
object(stdClass) (2) {
["id"]=>
string(1) "3"
["unit"]=>
int(0)
}
[8]=>
object(stdClass) (2) {
["id"]=>
string(1) "4"
["unit"]=>
string(1) "0"
}
[9]=>
object(stdClass) (2) {
["id"]=>
string(1) "5"
["unit"]=>
int(1)
}
}
Which means both arrays are literally merged. But what I wanted is since both arrays has common property called id and same value for it, it should become like:
array(2) {
[0]=>
object(stdClass) (2) {
["id"]=>
string(1) "1"
["text"]=>
string(5) "one"
["unit"]=>
int(0)
}
[1]=>
object(stdClass) (2) {
["id"]=>
string(1) "2"
["text"]=>
string(8) "two"
["unit"]=>
int(2)
}
}
Note that array1 has id, text while array2 has id and unit.
I did refer here as tried the first answer which suggest to use array_map(), but for me I'm getting error saying argument 1 is not an array.
Combine two arrays into a single array based on a common column value
EDIT:
tried this (doesn't work):
$array1 = array_walk($array1, function(&$value) { $value = (array) $value; })
$array2 = array_walk($array2, function(&$value) { $value = (array) $value; })
function modifyArray($a, $b)
{
if (!empty($a) && !empty($b)) {
return array_merge($a, $b);
} else if (!empty($a) && empty($b)) {
return $a;
} else if (empty($a) && !empty($b)) {
return $b;
}
}
$new = array_map("modifyArray", $array1, $array2);
var_dump($new);
Merging objects is noticeably more tedious than arrays. I'd be tempted to convert the array of objects to an array or arrays in my own project, but I won't for this solution.
Unlike arrays which can enjoy array_merge() or the union operator, objects need to be pushed in manually.
I am temporarily grouping data by using the id values as first level keys in the loop, then optionally sorting by those keys, then re-indexing the output to remove the temporary keys.
Code: (Demo):
$output = [];
foreach ($poorly_merged as $object) {
if (!isset($output[$object->id])) {
$output[$object->id] = $object;
} else {
foreach ($object as $property => $value) {
$output[$object->id]->{$property} = $value;
}
}
}
ksort($output); // optionally order by ids
var_export(array_values($output));
Or:
$output = [];
foreach ($poorly_merged as $object) {
if (!isset($output[$object->id])) {
$output[$object->id] = (object)[];
}
foreach ($object as $property => $value) {
$output[$object->id]->{$property} = $value;
}
}
ksort($output); // optionally order by ids
var_export(array_values($output));
Better practice would be not to merge your twp input arrays to form the $poorly_merged array. You could use iterate the second array of objects and add that data into the first -- this would be a more direct solution.
How can I fetch the value "3" from this set of arrays:
array(1) { [0]=> string(1) "1" }
array(1) { [0]=> string(1) "3" }
array(1) { [0]=> string(1) "0" }
The arrays are output from a foreach statement of parenting array, which is:
array(3) { [0]=> string(8) "St" [1]=> string(1) "1" [2]=> string(1) "0" }
array(3) { [0]=> string(16) "Fu" [1]=> string(1) "3" [2]=> string(1) "0" }
array(3) { [0]=> string(13) "Pa" [1]=> string(1) "0" [2]=> string(1) "0" }
Where I am going for the second line value: "Fu" [1]=> string(1) "3"
Maybe I am doing it wrong from the first array?
You're not giving us much to go on. Are the 3 arrays already in a parent array, in an object, etc.? Below is how to get the # 3 from the 3 arrays...but I'm guessing this is not actually what you are asking, we likely need much more detail...the real problem you are trying to solve.
function getThree($arr1, $arr2, $arr3) {
$array = array();
$array[] = $arr1;
$array[] = $arr2;
$array[] = $arr3;
foreach( $array AS $subArray ) {
// whichever condition works for you
if( $subArray[0] == 'Fu' || $subArray[1] == 3 ) {
return $subArray;
}
}
}
I am using php 5.2.10 i want to do the array_map on the array and i created a function for array mapping
function get_result(){
$result = mysql_query("Select * from table");
while($cr = mysql_fetch_array($result)){
$b = array_map(`calc`,$cr);
$rr_id = $cr['batch_id'].$cr['seq_id'];
$mqrrid = '999'.$rr_id;
$question_id = $cr['question_id'];
foreach ($b as $k => $v){
if(preg_match('{^Item \d+$}',$k)){
$new_insert[] = array(
'r_id'=>$mqrrid,
'q_id' =>$q_id,
'c_id' =>$k,
'rank'=>$v
);
}
}
}
}
function calc($n){
foreach($n as $m=> &$x) {
if (preg_match('{^Item \d+$}', $m)) {
if($x == null){
$x = $x;
}else {
$x = $x - 1;
}
}
}
return $n;
}
I don't know why I cannot call the function calc in array_map.....I cannot figure out the reason.....
Can anyone help me ?
original array :( actually the output after the array_map(calc,$cr) are same as follow)
array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["question_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "1"
["Item 2"]=>
string(1) "2"
["Item 3"]=>
string(1) "3"
["Item 4"]=>
string(1) "4"
["Item 5"]=>
string(1) "5"
["Item 6"]=>
NULL
what i need is : (minus the value of Item 1 to 6 by 1, if its null just leave it ~)
array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["q_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "0"
["Item 2"]=>
string(1) "1"
["Item 3"]=>
string(1) "2"
["Item 4"]=>
string(1) "3"
["Item 5"]=>
string(1) "4"
["Item 6"]=>
NULL
Finally, the result will become like this:(example of Item 1 and Item 6)
array(4) {
["r_id"]=>
string(5) "99911"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 1"
["rank"]=>
string(1) "0"
}
array(4) {
["r_id"]=>
string(5) "99916"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 6"
["rank"]=>
string(4) NULL
}
calc should be global, otherwise it cannot be found. Also, you should pass a string (no ` but rather enclose in ' or ").
Additionally, in general (if you used PHP 5.3), it is better to pass a function reference to the array_map function, instead of a string:
$func = function calc() { ... }
array_map($func, $cr);
I think you don't have to prepare the function for array_map.
function get_result($link_identifier = NULL) {
$result = mysql_query('Select * from table', $link_identifier);
$new = array();
while ($rows = mysql_fetch_assoc($result)) {
$r_id = '999' . $rows['batch_id'] . $rows['seq_id'];
foreach ($rows as $k => $v) {
if ($v !== null && preg_match('#^Item \\d+$#', $k)) {
$v = (string)((int)$v + 1);
}
$new[] = array(
'r_id' => $r_id,
'q_id' => $rows['question_id'],
'c_id' => $k,
'rank' => $v,
);
}
}
return $new;
}
Is there a way to set the value of members of an array with foreach?
<?
$arr = array(0=>'a',1=>'b',2=>'c',3=>'d');
foreach($arr as $key => $value){
$value = 'a';
}
var_dump($arr);
?>
returns:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
}
Where what I am trying to get it to return is:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "a"
[2]=>
string(1) "a"
[3]=>
string(1) "a"
}
Here is a link to the codepad I was using.
http://codepad.org/FQpPYFtz
$arr = array(0=>'a',1=>'b',2=>'c',3=>'d');
foreach($arr as $key => &$value) { // <-- use reference to $value
$value = 'a';
}
var_dump($arr);
It is quite simple:
foreach ($data as $key => $value) {
$data[$key] = 'new value';
}