I wanted to create three arrays within one MainArray.
The last two Arrays of the three Arrays, belong to one Variable.
How can I separate the two arrays from each other using a comma?
A simple "," wont be accepted, because the MainArray doesn't accept it.
I used explode, implode, join, but nothing worked, the system makes a comma output
but this comma isn't recognized as a coding comma to execute the separation of the two arrays.
$array0 = array("carparts"=>$carparts, "info"=>$info);
$i = 0;
while($i <= 1) {
$i++;
$array_season[$i] = array(
"carpartsseason" => $carpartsseason[$i],
"additional_s" => $info_s);
}
$MainArray = array(
$array0,
$array_season
);
As you can see, the comma behind the last $array0 works for the $MainArray.
But how do I get a comma behind every array of the array_season?
For example I added after while:
$display = '';
foreach($array_season as $new_output){
$display .= $new_output . ',';
}
recognize the comma behind $new_output ( . ',' ).
Then changed $MainArray:
$MainArray= array(
$array0,
$display
);
But without success. Same to join and implode.
(I worked on it for two days, but without results)
I think there is some confusion here over representations of arrays, the role of commas, and how to add and remove items from arrays.
Commas are used to separate different elements when declaring an array, e.g.:
$fruits = array( 'apple', 'banana', 'carrot' );
Each of the elements of that array is a string.
You can also add strings containing commas to an array:
$stuff = array( 'snow, falling', 'rain, pouring', 'sun, shining' );
The commas are within the elements of the array; they have no special powers over the structure of the array.
When you do this:
$display .= $new_output . ',';
you're adding a comma to the end of $new_output, and you're adding the whole string to the existing string $display. This won't form an array; when you later add $display to your existing array, $display is still just a long string with some commas in it, a bit like the strings in $stuff above.
If you want to add items to an array, you can either use array_push, or the more common shorthand notation:
# declare $display as an array
$display = array();
foreach($array_season as $new_output){
# add $new_output to the $display array
$display[] = $new_output;
}
I am not exactly clear on what structure you're looking for, but if you want to add the $array_season to your existing $MainArray, you can do so as follows:
# no need to create $array0 unless you need it elsewhere
$MainArray = array("carparts" => $carparts, "info" => $info);
$i = 0;
while($i <= 1) {
$i++;
$MainArray[] = array(
"carpartsseason" => $carpartsseason[$i],
"additional_s" => $info_s);
}
This will push the array containing ('carpartsseason' => $carpartsseason[$i], 'additional_s' => $info_s) directly on to $MainArray.
Create your 'MainArray':
$MainArray = array($array0);
Then in your while loop append each of the season arrays to the end of it with $MainArray[] =:
$i = 0;
while($i <= 1) {
$i++;
$MainArray[] = array(
"carpartsseason" => $carpartsseason[$i],
"additional_s" => $info_s);
}
Use array_merge:
$MainArray = array_merge($array0, $array_season);
Related
I am trying to group some foreach results based on the first 3 sets of characters.
For example i am currently listing sku codes for products and they look like this:
REF-MUSBOM-0500-ORA
REF-PROCOF-0001-LAT
REF-WHEREF-0001-TRO
REF-WHEREF-0001-ORA
REF-SHAKER-0700-C/B
REF-CREMON-0100-N/A
REF-GLUSUL-0090-N/A
REF-CRECAP-0090-N/A
REF-ALBFER-0120-N/A
REF-TSHCOT-LARG-BLK
REF-TSHCOT-MEDI-BLK
REF-ALBMAG-0090-N/A
REF-GYMJUG-2200-N/A
REF-OMEGA3-0090-N/A
REF-NEXGEN-0060-N/A
REF-VITAD3-0100-N/A
REF-SSSHAK-0739-N/A
REF-GINKGO-0090-N/A
REF-DIGEZY-0090-N/A
REF-VEST00-MEDI-N/A
REF-VEST00-LARG-N/A
REF-CREMON-0250-N/A
REF-MSM----0250-N/A
REF-GRNTEA-0100-N/A
REF-COLOST-0100-N/A
REF-GLUCHO-0090-N/A
REF-ZINCMA-0100-N/A
REF-BETALA-0250-N/A
REF-DRIBOS-0250-N/A
REF-HMB000-0090-N/A
REF-ALACID-0090-N/A
REF-CLA000-0090-N/A
REF-ACETYL-0090-N/A
REF-NXGPRO-0090-N/A
REF-LGLUTA-0250-N/A
REF-BCAA20-0200-N/A
REF-FLAPJA-0012-ACR
REF-FLAPJA-0012-MAP
REF-LCARNI-0100-N/A
REF-CORDYC-0090-N/A
REF-CREMON-0500-N/A
REF-BCAAEN-0330-APP
REF-PREWKT-0300-FPU
REF-TESFUS-0090-N/A
REF-AMIIFUS-0300-GAP
REF-AMIIFUS-0300-WME
REF-BCAINT-0400-FPU
REF-KRILLO-0090-N/A
REF-AMIIFUS-0300-PLE
REF-AMIIFUS-0300-FPU
REF-BCAINT-0400-WME
REF-ENZQ10-0090-N/A
REF-THERMO-0100-N/A
REF-LGLUTA-0500-N/A
REF-RBAR00-0012-DCB
REF-RBAR00-0012-PBC
REF-RBAR00-0012-WCR
REF-IMHEAV-2200-CHO
REF-PROCOF-0012-N/A
REF-DIEPRO-0900-STR
REF-DIEPRO-0900-BOF
REF-DIEPRO-0900-CHO
REF-INWPRO-0900-VAN
REF-INWPRO-0900-BOF
REF-INWPRO-0900-BCS
REF-INWPRO-0900-CHO
REF-INWPRO-0900-CMI
REF-INWPRO-0900-RAS
REF-INWPRO-0900-STR
REF-INWPRO-0900-CIN
REF-INWPRO-0900-CPB
REF-EGGPRO-0900-CHO
REF-EGGPRO-0900-VAN
REF-MICCAS-0909-CHO
REF-MICCAS-0909-CMI
REF-MICCAS-0909-VAN
REF-MICCAS-0909-STR
REF-BCAA50-0500-N/A
REF-MICWHE-0909-STR
REF-MICWHE-0909-VAN
REF-MICWHE-0909-CHIO
REF-MICWHE-0909-BAN
REF-1STOXT-2030-STR
REF-1STOXT-2030-VAN
REF-1STOXT-2030-CHO
REF-MUSBOM-0600-BCH
REF-MUSBOM-0600-FPU
REF-MUSBCF-0600-BCH
REF-MUSBCF-0600-FPU
REF-VEGANP-2100-STR
REF-VEGANP-2100-CHO
REF-INMPRO-2270-CPB
REF-DIETMR-2400-CPB
REF-INMPRO-2270-SCR
REF-INMPRO-2270-VIC
REF-MATRIX-1800-FRU
REF-INMPRO-2270-BOF
REF-MATRIX-1800-CHO
REF-INMPRO-2270-CHO
REF-ONESTO-2100-CHO
In the above list there are 2 skus which are:
REF-WHEREF-0001-TRO
REF-WHEREF-0001-ORA
The first 3 sets of characters split by - are the same. What would be the best approach of grouping all results leaving me an array something like this:
Array
(
[REF-WHEREF-0001] => Array
(
[0] => REF-WHEREF-0001-TRO
[1] => REF-WHEREF-0001-ORA
)
)
Are the first 3 groups (excluding the multiple -) always 13 characters? Then do something like this:
<?php
$arr = ["REF-MUSBOM-0500-ORA",
"REF-PROCOF-0001-LAT",
"REF-WHEREF-0001-TRO",
"REF-WHEREF-0001-PPL"];
$resultArr = [];
foreach ($arr as $sku) {
$resultArr[substr($sku, 0, 15)][] = $sku;
}
var_dump($resultArr);
If that length varies you might want to work with a regex or the strpos() of the third -.
I must say that I think you could come up with this yourself, since you were already thinking in the right direction i.e. foreach()
EDIT: Because I found other solutions more elegant looking, I decided to compare efficiency. This solution is a lot faster than the other ones.
I always create a new array with the index that I need for group, try this:
$arr=array('REF-MUSBOM-0500-ORA',
'REF-PROCOF-0001-LAT',
'REF-WHEREF-0001-TRO');
$newarr=array();
foreach($arr as $a){
$b=explode('-',$a);
array_pop($b);
$b=implode("-", $b);
$newarr[$b][]=$a;
}
echo '<pre>',print_r($newarr),'</pre>';
You will need to pick a group with some basics use of explode, implode and str_replace.
What does this solution do.
loop through the array of your items
explode to get last item index of exploded string assuming that it
would be dynamic in the end
implode & str_replace again to find out string of group name
And last strpos & in_array to have sample reponse
Solution
$array = array(
'REF-MUSBOM-0500-ORA',
'REF-PROCOF-0001-LAT',
'REF-WHEREF-0001-TRO',
'REF-WHEREF-0001-ORA',
'REF-SHAKER-0700-C/B',
'REF-CREMON-0100-N/A',
'REF-GLUSUL-0090-N/A',
'REF-CRECAP-0090-N/A',
'REF-ALBFER-0120-N/A',
);
$new_array = array();
foreach ($array as $key => $val) {
$group_arr = explode('-', $val);
$end = end($group_arr);
$combined_group = implode('-', $group_arr);
$group = str_replace('-' . $end, '', $combined_group);
if (strpos($val, $group) !== false && !in_array($group, $new_array)) {
$new_array[$group][] = $val;
}
}
echo '<pre>';print_r($new_array);echo '</pre>';
See demo on Sandbox
I'm doing something that is perhaps too long and strange to explain, but basically I've mapped a string in a complex way into an array in a way to make them jumbled up. This is an example of how it would look:
field[26][25]='x';
field[24][23]='z';
field[28][29]='y';
Now that I've successfully jumbled up the string in exactly the way I wanted, I need to reconstruct the linear result.
So I need to take row 1 of the array, and loop through all the elements in this row to combine them into a string. Then do the same thing with row 2 and so on to create one massive linear string.
How do I count how many rows and elements in those rows I have? For the life of me I cant even begin to find how to do this for multid arrays.
Kind regards
#u_mulder's got a solid answer there. For the number of elements, you'd just say:
$total = 0;
foreach( $matrix as $row ) $total += count($row);
For the concatenation of elements, you'd just say:
$concat = '';
foreach( $matrix as $row ) $concat .= implode('', $row);
Bob's your uncle. But really, is there a valid use case for such a strange mashup?
$field[26][25]='x';
$field[24][23]='z';
$field[28][29]='y';
$field_string = '';
array_walk_recursive ( $field , function($item, $key) use (&$field_string){
if(!is_array($item)){
$field_string .= $item;
}
});
echo $field_string;
Honestly, this is a little confusing. I may need more info but let me know if this helps
You can start with an empty string and use two nested foreach to iterate over lines and items on each line and append each item to the string:
$result = '';
foreach ($fields as $row) {
foreach ($row as $item) {
$result .= $item;
}
}
Or you can replace the entire inner foreach with $result .= implode('', $row);.
You can even replace the outer foreach with a call to array_map() then implode() the array produced by array_map() into a string:
$string = implode(
'',
array_map(
function (array $items) {
return implode('', $items);
},
$fields
)
);
I am trying to push values onto an array like so:
$scoreValues[$i][] = $percent ;
$scoreValues[$i][] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
I basically want to link together the $percent with the string, so I get an output like:
array (0 > array('46.5', '<span etc etc')
I then plan to sort by the percent sub-array so I have the highest scoring strings at the top.
Simplest way would be to use two arrays :
$percents[$i] = $percent;
$scores[$i] = "<span....>");
Or one array, but indexed like this
$data = new arrray('percents' => array(), 'scores' => array());
$data['percents'][$i] = $percent;
$data['scores'][$i] = "<span....>");
Once this is done, you then sort your arrays using array_multisort :
array_multisort(
$data['percents'], SORT_DESC,
$data['scores']);
In the second line you need to specify the index of the second array:
$scoreValues[$i][$j] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
So you basically need 2 counters, one for the external array ($i) and on for the internal array ($j).
EDIT:
You got me a bit confused with the question, seems like what you need is not a multi dimensinal array but rather a simple array:
$scoreValues[$percent] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;
Please note that this requires $percent to be unique.
Try this:
$val = array(
'percent' => $percent,
'html' => '<span id="item' . $i .
'" class="suggestElement" data-entityid="'.$row['id'].
'" data-match="'.$percent.'">'.rawurldecode($row['name']).
'</span>'
);
// This just pushes it onto the end of the array
$scoreValues[] = $val ;
// Or you can insert it at an explicit location
//$scoreValues[$i] = $val;
I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;
I have a variable holding values separated by a comma (Implode), and I'm trying to get the total count of the values in that variable. However. count() is just returning 1.
I've tried converting the comma-separated values to a properly formatted array which still spits out1.
So here is the quick snippet where the sarray session is equal to value1,value2,value3:
$schools = $_SESSION['sarray'];
$result = count($schools);
You need to explode $schools into an actual array:
$schools = $_SESSION['sarray'];
$schools_array = explode(",", $schools);
$result = count($schools_array);
if you just need the count, and are 100% sure it's a clean comma separated list, you could also use substr_count() which may be marginally faster and, more importantly, easier on memory with very large sets of data:
$result = substr_count( $_SESSION['sarray'], ",") +1;
// add 1 if list is always a,b,c;
Should be
$result = count(explode(',',$schools));
Actually, its simpler than that:
$count = substr_count($schools, ',') + 1;
If there is sarray key set in session array, the count will return 1 for an empty string as well.
$session = array('sarray' => '');
$count = count(explode(',', $session['sarray']));
echo $count;
// => 1
So, if you want to count the number of items in the array, you will have to add an additional check for empty.
$session = array('sarray' => '');
$count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
echo $count;
// => 0
Now, let's check if this works with items inside sarray.
$session = array('sarray' => 'foo, bar');
$count = !empty($session['sarray']) ? count(explode(',', $session['sarray'])) : 0;
echo $count;
// => 2
Hope this helps.
$schools = $_SESSION['sarray'];
$array = explode(',', $schools); array_walk($array, 'trim');
$count = count($array);
The array_walk($array, 'trim') will remove any trailing space in elements value. :)