I am making a session based shopping cart system, and I need some help with displaying the array from the session. My array looks like this:
array(5) { [0]=> NULL [1]=> string(5) "TMRS1" [2]=> string(5) "TMRS2" [3]=> string(5) "TMRS1" [4]=> string(5) "TMRS3" }
I would like a script to count duplicate elements and display them.
For instance, TMRS1 would be set to $name1 (= TMRS1) and $quantity1 (= 2). The next item would then be $name2 and $quantity2 and so on.
Is this possible? You are more than welcome to post if you've got a better idea on how I can display the items in the cart. I just have to be able to pull some data from a database by using the name of the items, and then add up all the prices of the items :)
maybe you can use array_count_values()
example from php.net
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
With the array you give:
$shopping_cart = array("TMRS1","TMRS2","TMRS1","TMRS3");
$items_count = array_count_values($shopping_cart);
echo "Number of TMRS1 in the cart:".$item_count["TMRS1"];
This would leave you with an array with the data you need:
<?php
$tmrs = array(NULL, "TMRS1", "TMRS2", "TMRS1", "TMRS3");
foreach ($tmrs as $key => $val){
$duplicateArray[$key]['name'] = "TMRS" . $key; // only the name
$duplicateArray[$key]['quantity'] = (int) str_replace("TMRS", "", $val); // aquire only the value
}
print_r($duplicateArray);
?>
That would return:
Array
(
[0] => Array
(
[name] => TMRS0
[quantity] => 0
)
[1] => Array
(
[name] => TMRS1
[quantity] => 1
)
[2] => Array
(
[name] => TMRS2
[quantity] => 2
)
[3] => Array
(
[name] => TMRS3
[quantity] => 1
)
[4] => Array
(
[name] => TMRS4
[quantity] => 3
)
)
You could then output the name or the value like this:
<?php echo $duplicateArray[2]['name']; ?>
Related
I have the following array
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 60b6a8a38cf91900695dd46b
)
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
I want to remove 60b6a8a38cf91900695dd46b from the multiple_assignee array.
I have tried with the following code:
if (($key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]), $mutipleAssignee)) !== false) {
unset($mutipleAssignee[$key]['accountId']);
}
But it is not removing that element. The intention is I don't want to repeat the 60b6a8a38cf91900695dd46b assignee in the multiple assignee array.
I have also tried with the following code:
foreach($mutipleAssignee as $subKey => $subArray){
if($subArray['accountId'] == $this->getUsersHashMapValue($responsiblePartyIds[0])){
unset($mutipleAssignee[$subKey]);
}
}
But it is resulting as
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
rather than
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
Thank you
Just extract the accountId column and search that. Then use that key:
$key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]),
array_column($mutipleAssignee, 'accountId'));
unset($mutipleAssignee[$key]);
After your edit it seems you just want to reindex the subarray after unset:
$mutipleAssignee = array_values($mutipleAssignee);
I would just use a simple for loop. All of the array_* functions are really helpful but I find that they hide nuances. Since I don't have your functions I'm just making a plain-old one, but you should be able to port this.
$data = [
'tags' => [
'hello',
],
'assignee' => '60b6a8a38cf91900695dd46b',
'multiple_assignee' => [
[
'accountId' => '60b6a8a38cf91900695dd46b',
],
[
'accountId' => '5b39d23d32e26a2de15f174f',
],
],
];
$assignee = $data['assignee'];
foreach ($data['multiple_assignee'] as $multiple_assignee_key => $multiple_assignee) {
// if the root assignee is also listed in the multiple assignee area
if ($multiple_assignee['accountId'] === $assignee) {
// remove the duplicate from the multiple area
unset($data['multiple_assignee'][$multiple_assignee_key]);
// re-index the array
$data['multiple_assignee'] = array_values($data['multiple_assignee']);
}
}
This outputs:
array(3) {
["tags"]=>
array(1) {
[0]=>
string(5) "hello"
}
["assignee"]=>
string(24) "60b6a8a38cf91900695dd46b"
["multiple_assignee"]=>
array(1) {
[0]=>
array(1) {
["accountId"]=>
string(24) "5b39d23d32e26a2de15f174f"
}
}
}
Demo here: https://3v4l.org/tYppK
Array1 ( [0] => [1] => [2] => 3 [3] => [4] => 5 [5] => [6] => )
Array2 ( [0] => URD [1] => ISL )
I want to map $array2 values to $array1 indexes (those having values 3 and 5) and I want get an array like this:
Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )
I have tried the following:
$newArray = array_values(array_filter(array_merge($array1,$array2)));
but the actual result is:
Array([0] => 3[1] => 5[2] => URD[3] => ISL)
The expected result should be:
Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )
Code
Try the following:
<?php
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
foreach($array1 as $id => $a1){
//for each item in array 1
if($a1){
//if the array 1 item has a value
$array1[$id] = array_shift($array2);
//replace it with an item from array 2
}
if(empty($array2)){
//if there are no more values left to share in array 2, stop
break;
}
}
var_dump($array1);
Output
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(3) "URD"
[3]=>
string(0) ""
[4]=>
string(3) "ISL"
[5]=>
string(0) ""
[6]=>
string(0) ""
}
Caveats
The method assumes that there will be values in both array 1 and array 2.
Once the values in array 2 have been split out and array 2 is empty, array 1 items with set values will no longer be affected.
The method does not care what the value set in array 1 is, just that there is a value.
Further reading
foreach()
array_shift()
Codepen
https://3v4l.org/RDQY6
This solution works and simple to understands as OPS requested...
<?
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
$i =0;
foreach($array1 as $keys=>$values) {
if($values == 3 || $values ==5) {
if(isset($array2[$i])){
$array1[$keys] = $array2[$i];
$i++;
}else { break; }
}
}
print_R($array1);
?>
it will replace the array2 values from array 1 values wherever 5 & 3 will come and which is independent of their sorting order.
example
$array1 = ["5", "", "3", "", "", "", ""]; will be converted into
$array1 = ["URD", "" ,"ISL","","",""];
if you want it in order like 3 should always come first then first sort array1 then use my code...
if you want 3 should be replace by URD and 5 should be replace by ISL
then you if codition will be different
Just another way to do it... (untested, but it should work)
<?php
$a = array ( 0 => '', 1 => '', 2 => 3, 3 => '', 4 => 5, 5 => '', 6 => '' );
$b = array ( 0 => 'URD', 1 => 'ISL' );
$c = array_replace ( $a, array_combine ( array_keys ( array_filter ( $a ) ), $b ) );
print_r ( $c );
?>
I have tried solutions to many similar questions, but they all seem to give me a count for each array. So I have the following array:
Array
(
[1] => Array
(
[0] => 1
[1] => 12
[2] => 2
)
[2] => Array
(
[0] => 1
[1] => 13
[2] => 3
)
[3] => Array
(
[0] => 1
[1] => 12
[2] => 2
)
[4] => Array
(
[0] => 1
)
[5] => Array
(
[0] => 1
)
)
I am trying to count the duplicates across all arrays. So the output should show:
Five 1's
Two 12's
One 13
Two 2's
At the moment I am trying:
foreach($data as $key => $row) {
print_r(array_count_values($row));
}
Which outputs the counts for each individual array
Array
(
[1] => 1
[12] => 1
[2] => 1
)
Array
(
[1] => 1
[13] => 1
[3] => 1
)
Array
(
[1] => 1
[12] => 1
[2] => 1
)
Array
(
[1] => 1
)
Array
(
[1] => 1
)
I have also tried this:
foreach ($data as $key => $row) {
$counts = array_count_values(array_column($data, $key));
var_dump($counts);
}
Which seems to miss a lot of information, like the count of the 1's
array(2) {
[12]=>
int(2)
[13]=>
int(1)
}
array(2) {
[2]=>
int(2)
[3]=>
int(1)
}
array(0) {
}
array(0) {
}
array(0) {
}
As a note, the initial array keys will not always be sequential, as this represents a row number. So this array may contain rows 1, 2, 5, 6, 7 etc.
How would I go about counting all duplicates together?
Since your array is not flattened, you will need to visit each value and increment unless you want to call merging functions.
Code: (Demo)
$array = [
1 => [1, 12, 2],
2 => [1, 13, 3],
3 => [1, 12, 2],
4 => [1],
5 => [1]
];
// make the generated value available outside of function scope
// \-------------------------------v--------------------------/
array_walk_recursive($array, function($v)use(&$output) { // visit each leafnode
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
});
var_export($output);
Output:
array (
1 => 5,
12 => 2,
2 => 2,
13 => 1,
3 => 1,
)
Or, non-recursively:
foreach ($array as $row) {
foreach ($row as $v) {
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
}
}
Or, a functional one-liner to flatten then count:
var_export(array_count_values(array_reduce($array, 'array_merge', array())));
Or, a functional one-liner with the splat operator to flatten then count:
var_export(array_count_values(array_merge(...$array)));
You can do this quite easily by using an accumulator array and iterating all the elements:
$result = [];
foreach ($data as $row) {
foreach($row as $value) {
$result[$value] = isset($result[$value]) ? $result[$value] + 1 : 1;
}
}
var_dump($result);
You can use call_user_func_array to merge all the individual arrays, and then array_count_values on that result:
$data = array
(array(1, 12, 2),
array(1, 13, 3),
array(1, 12, 2),
array(1),
array(1)
);
print_r(array_count_values(call_user_func_array('array_merge', $data)));
Output:
Array
(
[1] => 5
[12] => 2
[2] => 2
[13] => 1
[3] => 1
)
I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>
I have three following arrays.
Array ( [0] => 395 [1] => 295 )
Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg )
Array ( [0] => Seller Test Product [1] => Offline Product for Test )
The first array is the quantity, the second array is for the images, the third array is for the name of the products.
I want to combine all these three array into one and display it using foreach loop in PHP.
if I use array_merge(), I am getting the output:
Array ( [0] => 395 [1] => 295 ) Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg ) Array ( [0] => Seller Test Product [1] => Offline Product for Test ) Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg [2] => Seller Test Product [3] => Offline Product for Test [4] => 395 [5] => 295 )
Now, how can I display it using foreach loop in the view.
in the view the code is :
<?php foreach($c as $key => $strs)
{ ?>
<img style="width:150px;" src="<?php echo #getimagesize(base_url("assets/upload/product/".$key)) ? base_url("assets/upload/product/".$key):'http://placehold.it/350x200';?>" class="img-responsive">
<input type="text" name="vala" value="<?php echo $strs; ?>">
<input type="text" name="valas" value="<?php echo $strss; ?>">
<?php } ?>
Any help is welcome.
So what you really want is to group all fields of all arrays together. Values with the same index shall be merged into a single object. array_map() can be used for this.
$final = array_map(function($quantity, $image, $name) {
return (object)['quantity' => $quantity, 'image' => $image, 'name' => $name];
}, $quantityArray, $imageArray, $nameArray);
The result will be:
[
{
'qunatity' => 395,
'image' => '5a3a13f237715637629.jpeg',
'name' => 'Seller Test Product'
},
{
'qunatity' => 295,
'image' => '5a3b602654cfd527057.jpeg',
'name' => 'Offline Product for Test'
}
]
You can then address them in your foreach like this:
foreach($final as $product) {
echo $product->name;
echo $product->image;
echo $product->quantity;
}
For those of you who are in a real hurry, the following call to array_map() will do the same trick, but without mapping the array fields to a specific key in the new multidimensional array:
$final = array_map(NULL, $quantityArray, $imageArray, $nameArray);
The result will be:
[
[
0 => 395,
1 => '5a3a13f237715637629.jpeg',
2 => 'Seller Test Product'
],
[
0 => 295,
1 => '5a3b602654cfd527057.jpeg',
2 => 'Offline Product for Test'
],
]
The inner arrays of the newly created mltidimensinal array will be filled in the order of which the arrays were provided to array_map().
You can loop one array and use key to get the corresponding value from the other arrays.
$a=array ( 0 => 395,1 => 295 );
$b=array ( 0 =>" 5a3a13f237715637629.jpeg" ,1 => "5a3b602654cfd527057.jpg" ) ;
$c=array ( 0 => "Seller Test Product",1 => "Offline Product for Test" );
Foreach($a as $key => $val){
$res[$key]['qty'] = $val;
$res[$key]['img'] = $b[$key];
$res[$key]['desc'] = $c[$key];
}
Var_dump($res);
Output:
array(2) {
[0]=>
array(3) {
["qty"]=> int(395)
["img"]=> string(25) " 5a3a13f237715637629.jpeg"
["desc"]=> string(19) "Seller Test Product"
}
[1]=>
array(3) {
["qty"]=> int(295)
["img"]=> string(23) "5a3b602654cfd527057.jpg"
["desc"]=> string(24) "Offline Product for Test"
}
}
https://3v4l.org/h8B0u
Example Code
<?php
$array1=array ( 0 => 395,1 => 295 );
$array2=array ( 0 =>" 5a3a13f237715637629.jpeg" ,1 => "5a3b602654cfd527057.jpg" ) ;
$array3=array ( 0 => "Seller Test Product",1 => "Offline Product for Test" );
echo "<pre>";
print_r($array1);print_r($array2);print_r($array3);
$result=array_merge($array1,$array2,$array3);
print_r($result);
?>