Store unique values within foreach loop - php

Im trying to get value of ids for different values of a foreach loop but im confused how to go about it.
$revenue = array('pseudo1', 'pseudo2');
foreach ($revenue as $value) {
if (!$revenue_type) {
$st = getValueDescription($value);
foreach ($st as $stype) {
$tpe[] = $stype->id;
}
$rev[$value] = $tpe;
}
}
when i dump $rev this is what i get
array (size=1)
0 =>
array (size=3)
'pseudo1' =>
array (size=2)
0 => string '9' (length=1)
1 => string '19' (length=2)
'pseudo2' =>
array (size=4)
0 => string '9' (length=1)
1 => string '19' (length=2)
2 => string '1' (length=1)
3 => string '35' (length=2)
what i actually expect
array (size=1)
0 =>
array (size=3)
'pseudo1' =>
array (size=2)
0 => string '9' (length=1)
1 => string '19' (length=2)
'pseudo2' =>
array (size=4)
2 => string '1' (length=1)
3 => string '35' (length=2)
I need the result of my $rev to contain $value as keys but previous values of $tpe keeps adding up with each iteration, im confused how to achieve this.

Does this solve your problem?
$revenue = array('pseudo1', 'pseudo2');
$uniqueValues = [];
foreach ($revenue as $value) {
if (!$revenue_type) {
$st = getValueDescription($value);
$tpe = [];
foreach ($st as $stype) {
if (!in_array($stype->id, $uniqueValues)) {
$tpe[] = $stype->id;
$uniqueValues[] = $stype->id;
}
}
$rev[$value] = $tpe;
}
}
$uniqueValues holds the IDS you already added to the $rev variable, and the $tpe gets empty after every iteration

Related

php array count values in 4 deep array

Im trying to count how many times a delivery date is in my array but i seem to only be able to count the first level.
array (size=48)
'2000-01-01' =>
array (size=2)
'date' => string '2000-01-01' (length=10)
0 =>
array (size=2)
'van' => string '0' (length=1)
0 =>
array (size=619)
'drop' => string '0' (length=1)
0 =>
array (size=29)
'id' => string '18137' (length=5)
'order_number' => string '13550' (length=5)
'reference' => string '' (length=0)
'delivery_date' => string '2000-01-01' (length=10)
I've tried:
$counts = array_count_values(array_flip(array_column($output, 'delivery_date')));
and
$array = array_map(function($element){
return $element['delivery_date'];
}, $output);
$array2 = (array_count_values($array));
print_r($array2);
in the end i either end up with a array to string error or the value 1.
how Would i go about counting these?
Thanks.
You could make use of array_walk_recursive and increment an array value every time the delivery_date key is present in the array at any level:
$counts = [];
array_walk_recursive(
$output,
static function ($value, string $key) use (&$counts): void {
if ($key === 'delivery_date') {
$counts[$value] = ($counts[$value] ?? 0) + 1;
}
}
);

Sorting 'key=>value' pair multi-dimensional arrays in PHP

I am creating a site and I am trying to do a few complicated things with arrays to get it to work.
It is for an e-commerce site and each product on my site can have a number of attributes. I am trying to get each combination of attributes to do the pricing for them seperately.
First I get an array of the attribute ids ($attribute_id_array) and the query the database for the options for that array.
So if one attribute was colors the options here would be red,green,blue,etc,. or size would be small,medium,large,etc,. These are then stored in a new array ($attribute_arrays).
I then go through these to get every combination of attributes the product can have and sort these into a new array again ($new_attributes_array).
I then loop through this and create a price form for each combination.
$attribute_arrays = [];
foreach($attribute_id_array as $attribute_id){
$params = [$attribute_id];
$sql = "SELECT * FROM attributes WHERE id=?";
$attributeResult = DB::run($sql,$params);
while($row = $attributeResult->fetch(PDO::FETCH_ASSOC)){
array_push($attribute_arrays,$row);
}
}
var_dump($attribute_arrays);
function combinations($arrays, $i = 0) {
if (!isset($arrays[$i])) {
return array();
}
if ($i == count($arrays) - 1) {
return $arrays[$i];
}
$tmp = combinations($arrays, $i + 1);
$result = array();
foreach ($arrays[$i] as $v) {
foreach ($tmp as $t) {
$result[] = is_array($t) ?
array_merge(array($v), $t) :
array($v, $t);
}
}
return $result;
}
$new_attributes_array = combinations($attribute_arrays);
var_dump($new_attributes_array);
This is all working fine except I want to be able to get the keys for all of the key value pairs so I can reference it back to my database.
The way it comes out at the moment is like this:
$attribute_id_array:
array (size=2)
1 => string '5' (length=1)
2 => string '7' (length=1)
$attribute_arrays:
0 =>
array (size=2)
'attribute1' => string 'Step Through Bars' (length=17)
'attribute2' => string 'Gated' (length=5)
1 =>
array (size=2)
'attribute1' => string '3 metres' (length=8)
'attribute2' => string '6 metres' (length=8)
$new_attributes_array:
0 =>
array (size=2)
0 => string 'Step Through Bars' (length=17)
1 => string '3 metres' (length=8)
1 =>
array (size=2)
0 => string 'Step Through Bars' (length=17)
1 => string '6 metres' (length=8)
2 =>
array (size=2)
0 => string 'Gated' (length=5)
1 => string '3 metres' (length=8)
3 =>
array (size=2)
0 => string 'Gated' (length=5)
1 => string '6 metres' (length=8)
Is there a way to get it so that the key will be similar in format to:
0 =>
array (size=2)
5-attribute1 => string 'Step Through Bars' (length=17)
7-attribute1 => string '3 metres' (length=8)
1 =>
array (size=2)
5-attribute1 => string 'Step Through Bars' (length=17)
7-attribute2 => string '6 metres' (length=8)
Edit
So I changed the line array_push($attribute_arrays,$row); to $attribute_arrays[$attribute_id] = $row;.
This now means that $attribute_arrays now has the$attribute_id variable as the key like so:
array (size=2)
5 =>
array (size=2)
'attribute1' => string 'Step Through Bars' (length=17)
'attribute2' => string 'Gated' (length=5)
7 =>
array (size=2)
'attribute1' => string '3 metres' (length=8)
'attribute2' => string '6 metres' (length=8)
This now means my other function for getting the combinations won't work as it is using the $i variable as the index for the array starting at '0'.
Found another function online to sort it here How to generate in PHP all combinations of items in multiple arrays:
function combinations($arrays) {
$result = array(array());
foreach ($arrays as $property => $property_values) {
$tmp = array();
foreach ($result as $result_item) {
foreach ($property_values as $property_key => $property_value) {
$tmp[] = $result_item + array($property_key => $property_value);
}
}
$result = $tmp;
}
return $result;
}
However, this doesn't do exactly as I want and I end up with this:
array (size=4)
0 =>
array (size=1)
'attribute1' => string 'Step Through Bars' (length=17)
1 =>
array (size=2)
'attribute1' => string 'Step Through Bars' (length=17)
'attribute2' => string '6 metres' (length=8)
2 =>
array (size=2)
'attribute2' => string 'Gated' (length=5)
'attribute1' => string '3 metres' (length=8)
3 =>
array (size=1)
'attribute2' => string 'Gated' (length=5)
try this as your combinations function
modified code taken from here
function combinations($arrays) {
$result = array(array());
foreach ($arrays as $key => $values) {
$tmp = array();
foreach ($result as $item) {
foreach ($values as $k=>$value) {
$tmp[] = array_merge($item, array($key.'-'.$k => $value));
}
}
$result = $tmp;
}
return $result;
}
Instead of using while on following line
while($row = $attributeResult->fetch(PDO::FETCH_ASSOC)){
Use foreach loop to get key paired value. e.g
foreach($databaseFetchedRecord as $mykey=>$myvalue)

json string to php array

I have this json string as below:
$json = '[{"sessionNo":"1","sessionData":["4","6"]},{"sessionNo":"2","sessionData":["2"]},{"sessionNo":"3"}]';
I want to "translate" it as a PHP array. I tried to do the following but it returns an empty array :
var_dump(json_decode($json))
**UPDATE**
Now I am getting this:
array (size=3)
0 =>
array (size=2)
'sessionNo' => string '1' (length=1)
'sessionData' =>
array (size=2)
0 => string '4' (length=1)
1 => string '6' (length=1)
1 =>
array (size=2)
'sessionNo' => string '2' (length=1)
'sessionData' =>
array (size=1)
0 => string '2' (length=1)
2 =>
array (size=1)
'sessionNo' => string '3' (length=1)
I want to loop through this array so I get for each sessionNo the corresponding SessionData, smth like:
sessionNo SessionData
1 4
1 6
2 2
You can use something like...
$json = '[{"sessionNo":"1","sessionData":["4","6"]},{"sessionNo":"2","sessionData":["2"]},{"sessionNo":"3"}]';
$array = json_decode($json, true);
foreach ( $array as $session ) {
if ( isset ($session['sessionData'])){
foreach ( $session['sessionData'] as $data ) {
echo $session['sessionNo']."-".$data.PHP_EOL;
}
}
}
This is just converting the data and then loop over the arrays in a foreach(), only doing the inner one if there is any sessionData.
This outputs..
1-4
1-6
2-2

Show duplicate value in array only one but show all others

can i showing only one value in foreach array having multiple same value, without grouping the array firstly in the query like this :
0 =>
array (size=10)
'id' => string '1' (length=1)
'questionname' => string 'question 01' (length=36)
'answerspossible' =>
array (size=3)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
2 =>
array (size=2)
...
'answer' => string 'YES' (length=3)
'answer2' => string '' (length=0)
1 =>
array (size=10)
'id' => string '1' (length=1)
'questionname' => string 'question 01' (length=36)
'answerspossible' =>
array (size=3)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
2 =>
array (size=2)
...
'answer' => string 'YES' (length=3)
'answer2' => string 'test answer' (length=0)
Result i want in the view is to group by the questioname inside the foreach :
question 01 :
- answer & answer 2
- answer & answer 2
My code is :
foreach ($Questions as $Key => $Question) {
echo $question['questionname'];
echo $Question['answer']." & ".$Question['answer2'];
}
thnx for help :)
$justblank = ''; // just a blank variable we will use it later.
foreach ($Questions as $Key => $Question) {
echo $question['questionname'];
$questionanswers = $Question['answer']." & ".$Question['answer2'];
if($justblank == $questionanswers){
break;
}else{
echo $questionanswers;
}
$justblank .= $questionanswers;
}
Hi Mohammed, I hope this help you :).
a blank var work
$justblank = -1;
foreach ($Questions as $Key => $Question) {
if($Question['id']!=$justblank){
echo $Question['questionname'];
$justblank=$Question['id'];
}
....
}

Php Convert Multidimensional array to string

Below is my function:
public function getChildrenId(){
$child_id = array($this->db->query("SELECT customer_id
FROM " . DB_PREFIX . "customer
WHERE parent IN ( " .(int)$this->customer->getId().") "));
foreach($child_id as $id =>$value) {
$conv = json_decode(json_encode($value), true);
$final = array_slice($conv,2);
foreach ($final as $gchildren => $key) {
sort($key);
$gr = array_slice($key,0,$this->INF);
}
}
return $gr;
}
It outputs:
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
I am trying to get the values of the nested arrays. When I use foreach I only get data from array[0]. I also tried slicing the parent array and still didn't get it right, it outputs array,array,array.
I would like to extract these arrays values to a new array that I can use to query the database. final_array = array (2,4,7).
Thank you in advance!
If your array looks like this, then the foreach should create the array your looking for.
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
The following php will output array(2,4,7);
<?php
$aNewArray = array();
foreach($aArray as $aArray){
$aNewArray[] = $aArray['customer_id'];
}
var_dump($aNewArray);
?>
You dont need a multidimensional array for this though.

Categories