I am trying to loop through each key but i am facing a problem of same value repeating inside for each loop
Please be noted we should keep on same code structure multiple foreach it's requirement i already posted this question here but didn't get solution instead of solution entire new code as answer imposed on me and nobody is actually taking care of it
Here is example of my current code and result (click here)
here is my code so far
<?php
$data2 = array(
'category_name' => '33287*100*prescription*1,32457*1250*lab*1'
);
$result = array('0' => (object)$data2);
foreach ($result as $key => $category) {
$category_name = explode(',', $category->category_name);
}
$newresults=[];
foreach ($category_name as $key) {
$category->category_name = $key;
$newresults[]=$category;
}
$result=$newresults;
$newresults=[];
$category->items_count = 0;
foreach ($result as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value->category_name);
// $category->items_count += count($sale_value);
$newresults[]=$category;
}
$result=$newresults;
i am getting the wrong results like this
Array
(
[0] => stdClass Object
(
[category_name] => 33287*100*prescription*1
)
[1] => stdClass Object
(
[category_name] => 33287*100*prescription*1
)
)
As noted, because you are reusing variable names, and also using them when their scope might not be correct or accepted, you are causing some confusion.
The code below brings the bottom loop inside of the top loop, because that's where the context really lives. Creating a temporary loop only adds to the potential confusion. If that doesn't work with the additional logic, more changes will be needed. I also changed a bunch of the variable names to hopefully make things more obvious. See the comments in the code for more details.
$reporting_data = array(
'category_name' => '33287*100*prescription*1,32457*1250*lab*1,32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1,32468*950*lab*1,32470*950*lab*1,33291*2500*lab*1,33292*2500*lab*1,47516*2000*lab*1,49209*0*lab*1,56835*2400*lab*1,56836*2400*lab*1',
'patient' => '28370',
'date' => 1643030497,
'ref' => '371',
);
// Create array of objects
$reporting_data_as_objects[] = (object)$reporting_data;
$results = [];
foreach ($reporting_data_as_objects as &$obj) {
// Setup base data that is shared across all items
$obj->reception_data_sum = 0;
$obj->references_data_sum = 0;
$obj->actual_price = 0;
$category_names = explode(',', $obj->category_name);
// Loop over the comma-delimited parts of category_name
foreach ($category_names as $category_name) {
// Clone our template object
$tmp = clone $obj;
// The second item of the asterisk-delimted field is the price
// We used $_ to indicate that we aren't interested in the first item.
list($_, $sale_value) = explode('*', $category_name);
// Set object-specific fields on our clone
$tmp->category_name = $category_name;
$tmp->actual_price = (int)$sale_value;
// Add the clone to the array
$results[] = $tmp;
}
}
// Always unset by-ref variables of a foreach
unset($obj);
print_r($results);
Demo here: https://3v4l.org/95KAQ
Related
I have an associative array
array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
)
What i Want to do is catch all the array keys where the key name has similarities
for example
i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values
Thanks For the help
Use the funtion array_keys
$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);
Unless you do not provide more code this will give you all the keys of $yourArray
Reference - array_keys
To get all the similar keys you can use this function similar-text()
Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.
Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.
The obvious tool is regular expressions:
$original_data = array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
);
$redacted_data = array();
foreach ($original_data as $key => $row) {
if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
$redacted_data[$matches[1]][$matches[2]] = $row;
} else {
$redacted_data[$key][] = $row;
}
}
var_dump($redacted_data);
It should be easy to tweak for your exact needs.
I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:
foreach ($redacted_data as $k => $v) {
foreach ($v as $kk => $vv) {
printf("(%s,%s) = %s\n", $k, $kk, $vv);
}
}
<?php
$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
$itempos = strpos("item_name", $key);
if ($pos !== false)
$items[]=$val;
$numberpos = strpos("item_number", $key);
if ($numberpos !== false)
$itemsNumbers[]=$val;
}
?>
Note: here $itemarr is your input array
$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers
I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}
public function GetOpsPremiums()
{
// Get the Cost Multiplier
$costMulti = $this->GetCostMultiplier();
// Get the Prem Ops
$premOps = $this->GetPremOpsEL();
// Get the Factors
$factors = $this->GetFactors();
// Get the full class array
$classArray = $this->GetClassArray();
foreach ($classArray as $key => $values) {
$classTotalHalved = $values / 1000;
$mainMultiplier = $costMulti * $premOps[$key] * $factors[$key]['premops'];
$premium = $classTotalHalved * $mainMultiplier;
$opsPremiums = array(
$key => round($premium)
);
}
return $opsPremiums;
}
I want $opsPremiums to not just iterate 1 at a time. I need it to iterate and add itself to itself.
I tried
foreach ($opsPremiums as $key2 => $values2) {
$opsPremiums = array(
$key => round($premium)
);
}
Can someone explain to me what I need to do in order to get the $opsPremium to stack itself neatly into a single array?
should be so
foreach ($opsPremiums as $key2 => $values2) {
$opsPremiums[] = array(
$key => round($premium)
);
}
I'm a little unsure of what you mean, but are you trying to return all the results in $opsPremium?
The issue is your setting it as an array on each iteration rather than adding to it.
$opsPremium = array();
foreach ($classArray as $key => $values) {
$classTotalHalved = $values / 1000;
$mainMultiplier = $costMulti * $premOps[$key] * $factors[$key]['premops'];
$premium = $classTotalHalved * $mainMultiplier;
$opsPremiums[] = array(
$key => round($premium)
);
}
return $opsPremiums;
Storing $opsPremium outside the loop and adding to it each time will do that for you.
My apologies if this is not what you were asking.
It seems your very confused with the terminology of how to speak about your problem. I believe what you should have asked is, I want to add some extra items including itself to an array for return. In which case the magic you need is array concatenation. Im a little unsure of what your array requires, but you can append anything to any php array with the [] operator. If you respond with a more detailed question perhaps I can help you further.
Depending on what your are adding to your array, for the program to function you may need to use the array_merge, array_push.
In a mysql database I store some image names without the exact path.
So what I like to do is add the path before I load the returned array into jQuery (json) to use it in the JQ Galleria plugin.
In the columns I've got names likes this:
11101x1xTN.png 11101x2xTN.png 11101x3xTN.png
Which in the end should be like:
./test/img/cars/bmw/11101/11101x1xTN.png
./test/img/cars/bmw/11101/11101x2xTN.png
I could just add the whole path into the database but that seems 1. a wast of db space. 2. Then I need to update he whole db if the images path changes.
I could edit the jQuery plugin but it doesn't seem practical to update the source code of it.
What is the right thing to do and the fasted for processing?
Can you add a string after you make a db query and before you fetch the results?
part of the function where I make the query:
$needs = "thumb, image, big, title, description";
$result = $get_queries->getImagesById($id, $needs);
$sth=$this->_dbh->prepare("SELECT $needs FROM images WHERE id = :stockId");
$sth->bindParam(":stockId", $id);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
this is the foreach loop:
$addurl = array('thumb', 'image', 'big');
foreach ($result as $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
}
}
}
the array looks like this:
Array
(
[0] => Array
(
[thumb] => 11101x1xTN.png
[image] => 11101x1xI.png
[big] => 11101x1xB.png
[title] => Title
[description] => This a blub.
)
)
The url should be add to thumb, image and big.
I tried to change the array values using a foreach loop but that didn't work. Also not noting if the use of that would course a unnecessary slowdown.
well, you almost nailed it. only thing you forgot is to store your $val back in array.
foreach ($result as $i => $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
$result[$i][$item] = $val;
}
}
}
however, I'd make it little shorter
foreach ($result as $i => $array) {
foreach ($addurl as $item) {
$result[$i][$item] = '/test/img/cars/bmw/11101/'.$array[$item];
}
}
}
Assuming your array looks like this:
$result = array("11101x1xTN.png", "11101x2xTN.png", "11101x3xTN.png");
A simple array_map() can be used.
$result_parsed = array_map(function($str) { return './test/img/cars/bmw/11101/'.$str; }, $result);
As seen Here
I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.
$results = array();
foreach($this->columns as $column){
$current = array();
while($row = mysql_fetch_array($this->results)){
$current[] = $row[$column];
print_r($current);
echo '<br><br>';
}
$results[$column] = $current;
}
print_r($results);
return mysql_fetch_array($this->results);
This works, but the while loop only works on the first column. The print_r($results); shows the following:
Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )
Can anybody shed some light?
Thanks in advance!
It's because you already fetched every row, and the internal pointer is at the end.
The next while, mysql_fetch_array() will immediately return false.
You can reset the pointer to the first row:
mysql_data_seek($this->results, 0);
Put this just before
while($row = mysql_...
I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:
foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value
}