php - build array out of computations from multidimensional array - php

This is driving me nuts.
I'm attempting to reada CSV file (done) and then work through the permutations of each row.
Each row contains several bits of data (name, price etc.).
Some of them contain slash separated lists (a/b/c/c3/c65).
What I need to do is generate all the possible variations of each row.
Example:
Row 12 =
Name = name,
Price = price,
Models = x12/x14/x56,
Codes = LP1/LP12/LP899/XP90/XP92,
From that I should be able to generate 15 variations, each with the same Name and Price, but with different Codes and varied Models;
Name Price X12 LP1
Name Price X12 LP12
Name Price X12 LP899
~
Name Price X56 XP90
Name Price X56 XP92
Yet I'm either overwriting pre-existing versions, or generating individual versions, but only getting 1 set of values changing (so I may get the 15 versions, but only Model changes, everything else stays the same).
Any help/thoughts or pointers would be appreciated!

So you have one row containing that much items,
say
$row = array('Name'=>'name', 'price'=>'price','models'=>'x12/x14/x56','codes'=>'LP1/LP12/LP899/XP90/XP92')
and you want to split models and codes with "/" then have each item as a new row in the array with all the columns those having the same value for price and name field, here is how you can do this,
$line = 0;
$result_array = array();
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price'];
//split the models using explode
$tmpModels = explode("/",$row['models']);
foreach($tmpModels as $mod){
if($line > 0){
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price'];
}
$result_array[$line]['model'] = $mod;
$line++;
}
$line = 0;
//now split the codes using explode
$tmpCodes = explode("/",$row['models']);
foreach($tmpCodes as $cod){
$result_array[$line]['code'] = $cod;
$line++;
}
if(count($tmpCodes) > count($tmpModels)){ // then few more rows should be added to include all from codes
foreach($tmpCodes as $cod){
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price]'
$result_array[$line]['model'] = '';
$result_array[$line]['code'] = $cod;
$line++;
}
}
$result_array will have what you want.
This code is not tested, so there can be some errors, btw i hope this will surely give you an idea on how to achieve that.

Let's say you have array that looks like this:
$variant=Array();
$list[0]=array('Name'=>'Item name', 'Price'=>'$400','Models'=>'x12/x14/x56','Codes'=>'LP1/LP12/LP899/XP90/XP92');
$list[1]=array('Name'=>'Item name', 'Price'=>'$400','Models'=>'x12/x14/x56','Codes'=>'LP1/LP12/LP899/XP90/XP92'); // and more array.......
for($i=0;$i<count($list);$i++){
$Names=$list[$i]["Name"];
$Prices=$list[$i]["Price"];
$Models=explode("/",$list[$i]["Models"]);
$Codes=explode("/",$list[$i]["Codes"]);
for($i2=0;$i2<count($Codes);$i2++){
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[0],"code"=>$Codes[$i2]);
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[1],"code"=>$Codes[$i2]);
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[2],"code"=>$Codes[$i2]);
// You can add more models by copy paste it and change $Models[2] with next available $Models array index
}
}
var_dump($variant);
?>
The results will produce 30 array, because we have 2 rows, so that's not wrong ... okay
Reason for looping the codes
Because codes is more greater than models. So, we can catch all values.
Good luck, btw i have test it and that's worked

Related

hide certain category from single post

I need to limit number of categories display in a single post on wordpress using this script
function swift_list_cats($num){
$temp=get_the_category();
$count=count($temp);// Getting the total number of categories the post is filed in.
for($i=0;$i<$num&&$i<$count;$i++){
//Formatting our output.
$cat_string.=''.$temp[$i]->cat_name.'';
if($i!=$num-1&&$i+1<$count)
//Adding a ',' if it’s not the last category.
//You can add your own separator here.
$cat_string.=' | ';
}
echo $cat_string;
}
But I also need to hide some categories. How would I do that?
Simple answer is to return a new count not based on the length of your array so
for($i=0;$i<$num&&$i<$count;$i++){
becomes:
for($i=0;$i<10;$i++){
or use $temp = array_slice(get_the_category(), //ofset 0, //length 10);
Array slice info can be seen here.
If you need to hide some values, this would be far easier to do by adding a hidden column to your database and select values WHERE hidden = 0. However to address your question.You need to know which values you want to hide. Store these in an array and do the following.
function swift_list_cats($num){
$hiddenArray = [12, 105];
//change offset and limit to what you desire removing the slashes and labels
$temp = array_slice(get_the_category(), 0, 10);
$count=count($temp);
$cat_string = '';
for($i=0;$i<$num&&$i<$count;$i++){
if(in_array($temp[i]->cat_ID, $hiddenArray)){
continue;
}
$cat_string.=''.$temp[$i]->cat_name.'';
if($i!=$num-1&&$i+1<$count)
$cat_string.=' | ';
}
echo $cat_string;
}
$hiddenArray is the array you populate with your category IDs that you want hidden

PHP: Separate Area Code from Phone number with MySQL Database

I want to separate the area code from a phone number string by using a area code mysql database.
For example the string is 0349152023.
The endresult should be 03491 52023.
To get the endresult, i want to split the string and search every digit in database.
For example 0 and then 3 and then 4 and then take the last found result.
The code i have at the moment is only to prepare the phone number string for futher actions:
$phone1 = preg_replace('/[oO]/', '0', $phone-string);
$phone2 = preg_replace("/[^0-9]/", "", $phone1);
Then i use str_split to cut the string in pieces:
$searchArray = str_split($phone2);
Thanks for your help.
You may build an array containing all the area codes.
Then you may write something like this:
foreach ($area_codes as $code) {
if (substr($phone, 0, strlen($code)) == $code) {
$phone_string = substr($phone, 0, strlen($code))." ".substr($phone, strlen($code));
}
}
You can obviously add a controller in order to verify if the area code was found or not.
step 1: select all area codes from db and put them into an array $areaCodes
step 2: iterate over $areaCodes as $code and check if the phonenumber starts with $code. if it does, create a string that has a whitespace between the code and the rest of the number
$phonenumber = '0349152023';
$preparedPhonenumber = '';
foreach($areaCodes as $code){
if(str_pos($phonenumber, $code) === 0){
// phonenumber starts with areacode
$phoneWithoutCode = substr($phonenumber, strlen($code));
$preparedPhonenumber = $code.' '.$phoneWithoutCode;
break;
}
}
// if one of the areaCodes was 0349,
// the variable $preparedPhonenumber is now '0349 152023'
edit: you can shorten the amount of returned area codes from db by selecting only those that start with a certain string.
Let's assume the shortest area code in germany is 3 digits long (which i think is correct).
$threeDigits = substr($phonenumber,0,3);
$query = "SELECT * from areacodes
WHERE code like '".$threeDigits."%'
ORDER BY CHAR_LENGTH(code) DESC";
this will drastically shrink down the probable area codes array, therefore making the script faster.
edit 2: added order by clause in query so the above code will check for longer areacodes first. (the break; in the foreach loop is now obligatory!)
Hi Leonardo Gugliotti and Cashbee
i sort the areaCodes to get a better match. The php scripts works fine, but takes to long time to handle 5000 MySQL entries. Is it possible to make the foreach search directly in mySQL?
<?php
$sample_area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
sort($sample_area_codes);
$phone_string = '0349152023';
foreach ($sample_area_codes as $code) {
$subString = substr($phone_string, 0, strlen($code));
if ($subString == $code) {
$phone = $subString." ".substr($phone_string, strlen($code));
}
}
if (!empty($phone)) {
echo $phone;
}
else {
echo "No AreaCode found.";
}
?>
Output: 034915 2023, which is correct
A single probe (assuming INDEX(area_code)):
SELECT ...
FROM AreaCodes
WHERE area_code < ?
ORDER BY area_code DESC
LIMIT 1;
(Where you bind the $phone_number as a string into the ?)
I think you'd better split your database into a tree, making a table for each digit.
So the third digit could refer to the second, the fourth to the third, and so on until you reach the maximum lenght of the prefix. The last table should include the name of the area.
Following your example, supposing that the maximum lenght of the area code was five digits, the fifth_digit_table should have at least four fields like these:
ID
IDref
Number
Name
10 records may have the same IDref, corresponding to the number "2" at the fourth position, linked to the previous "021" through the fourth_digit_table, the three_digit_table and so on; only one among these records, that with the Number field filled with "9", should have the Name "Haan"; the others, if there aren't any, should have the Name "Solingen".
I hope you will manage to speed up your script.

Woocommerce Order / AFC get_sub_field / get_sub_field_object (array)

Have setup ACF repeater field that stores various amount of tracking numbers in the order. Having 0 success with retrieving this information so need some advice.
Am using this to put information in subfields and it does the job
foreach ($base->DocumentLines->DocumentLine as $item) {
foreach ($item->MiscData as $misc) {
foreach ($misc->PackageNo as $package) {
$trackno = (string)$package->TrackingNo;
update_post_meta("$order_id", $field_rep, $count);
$sub = $count +1;
update_sub_field(array($field_key_rep, $sub, $field_key_sub), $trackno, "$order_id");
$count = $count + 1;
update_field($field_key, $trackno, "$order_id");
}
}
}
This works well, but then i need to retrieve this numbers and write em out. They are getting included in an email so need to retrieve the data outside of order.
Before rebuilding the function to be able to handle multiple numbers i did use a single field and could retrieve the information with
get_post_meta($order_id, 'tracking', true);
Feels like i have been trying everything now but got absolutely nothing.
Image from one of the orders, in this one it’s 10 tracking numbers but it varies from 1 to 20 if it's to any help.
The feeling when you realize after 10 hours that your missed a capital letter in sub field name.
Just wanted to submit my solution and hopefully it can help someone else having issues with ACF Repeater fields + Woocommerce
For my specific case i did make a function that could extract all the tracking numbers my function above did add from XML files.
$function trackingNo($postID) {
$field_rep = 'trackingNo';
$field_sub = 'no';
if (have_rows($field_rep, $postID)) {
$trackingNo = array();
// loop through the rows of data
while (have_rows($field_rep, $postID)):
the_row();
// Add to array
$trackingNo[] = get_sub_field($field_sub);
endwhile;
$foo = implode('&consignmentId=', $trackingNo);
$bar = 'urlzz/tracktrace/TrackConsignments_do.jsp?&consignmentId=';
$value = $bar . $foo;
return $value;
}
}
Any advice for improvement is always welcome, my PHP is so'n'so :)

String from an array from an array from the database

Okay so, first of all, I searched through the www for this question, and I found some question related to arrays but not exactly to mine.
Okay so as you may know, paypal only allows one custom variable to be $POST but I need to gather the product id AND the quantity of the item bought. So to do this I made my custom variable into something that would get the post like (25-1,12-3,13-4) it means, the user bought 3 items(separated by commas), where the first number is the product id (then the separator '-' comes in) and the second one is the quantity. (so they're all in the same row and column)
Now my problem is displaying it from the database. I need to get the product name and details that's why I need to separate the numbers from each array as a string and fetch the data from the database for the information of the product. (I'm using an older version of php anyway, 5.2, I guess.)Now the problem is:
1.) It returns the word 'Array' (literally) so it would say like ArrayArrayArray
2.) How do I explode/separate those data so I can get it because I need the product ID to fetch some other data... I tried exploding it into array, then exploding it again but doesn't work (most likely my code is wrong?)
Here is my code: (I've already connected to the database)
$data = mysql_query("SELECT * from transactions") or die(mysql_error());
/* My table tag and headers goes here */
while($info = mysql_fetch_array( $data )) {
echo "<tr>";
echo '<td>' . $info['id'] . '</td>';
echo "<td>";
$array = $info['product_id_array'];
$explode_array = explode(",", $array);
foreach($explode_array as $explode_more){
$explode_more = explode("-", $explode_array);
$prod_id = $explode_more[0];
$quantity = $explode_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
echo"</td>";
echo"<tr>";
}
If only paypal would allow multiple custom variables T_T Thank you guys. Forgive me if I can't express my question very well or my language is not good, as english is not my first language :), Good day!
Your variable names are mixed up. Inside the foreach-loop, you should do something like this
foreach($explode_array as $explode_more){
$explode_even_more = explode("-", $explode_more);
$prod_id = $explode_even_more[0];
$quantity = $explode_even_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
Note, that $explode_more is used inside the loop and $explore_array is left as is.
Separate this in multiple tables, never store non-atomic values in 1 column.
Certainly not when they have relation with another table.
Suppose you want to know the sales from a certain product in some period.

Creating a different array related to different times a loop happens php

there. I'm having a problem with creating arrays in certain conditions in php, i'll try to explain. Here's my code:
for ($i = 1; $i < $tamanho_array_afundamento; $i++) {
if ($array_afundamento[$i] - $array_afundamento[$i - 1] > 1) {
$a = $array_afundamento[$i - 1];
$con->query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
$tabelas_intervalos_afunda1 = ($con->query("SELECT * FROM afunda_$a");
while ($row = $tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC)) {
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
$prevNum = $a;
}
}
So as u can see, i have an if statement in a for loop, what i'm wishing to do is to create
one set of:
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
every time the if statement is runned. I was trying replacing this in the original code:
{
$array_forma_onda_fase1_afund_$a[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_$a[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_$a[] = $row['L3_forma_tensao'];
}
so as $a is changed everytime the if statement is accessed, i could have a different set of these arrays for everytime the if statement is accessed, but php doesn't accept this and i wouldn't have a very good result, though if i can reach it i would be pleased.
But my goal is to get:
{
$array_forma_onda_fase1_afund_1[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_1[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_1[] = $row['L3_forma_tensao'];
}
{
$array_forma_onda_fase1_afund_2[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_2[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_2[] = $row['L3_forma_tensao'];
}
...
where the last number represents the array retrieved for the n-th time the if statement runned. Does someone have a tip for it?
Thanks in advance! Would appreciate any help.
EDIT
As asked, my real world terms is as follows:
I have a table from which i need to take all the data that is inside a given interval. BUT, there's a problem, my data is a sine function whose amplitude may change indefinite times (the data bank is entered by the user) and, when the amplitude goes inside that interval, i need to make some operations like getting the least value achieved while the data was inside that interval and some other parameters, for each interval separately, (That's why i created all those tables.) and count how many times it happpened.
So, in order to make one of the operations, i need an array with the data for each time the databank entered by the user goes in that interval (given by the limits of the create query.).
If i were not clear, just tell me please!
EDIT 2
Here's the image of part of the table i'm working with:
http://postimg.org/image/5vegnk043/
so, when the sine gets inside the interval i need, it can be seen by the L1_RMS column, who accuses it, so it's when i need to get the interval data until it gets outside the interval. But it may happens as many times as this table entered by the user brings it on and we need to bear in mind that i need all the intervals separately to deal with the data of each one.
Physics uh?
You can do what you wanted with the arrays, it's not pretty, but it's possible.
You can dynamically name your arrays with the _$a in the end, Variables variables, such as:
${"array_forma_onda_fase3_afund_" . $a}[] = "fisica é medo";

Categories