How to build a bidimensional array in PHP? - php

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;

Related

Double Array, Comma Separation not accepted

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);

How to add variables that are passed on through the URL to an array?

<?php
$i = $_GET['i'];
echo $i;
$values = array();
while ($i > 0)
{
$expense = $_GET['expense_' + i];
$amount = $_GET['amount_' + i];
$values[$expense] = $amount;
i--;
print_r($values);
}
?>
i represents the number of sets of variables I have that have been passed through from the previous page. What I'm trying to do is add the expenses to the amounts and put them in an array as (lets just say for this example there were 3 expenses and 3 amounts) [expense_3 => amount_3, expense_2 => amount_2, expense_1 => amount_1]. The names of the variables are successfully passed through via the url as amount_1=50, amount_2=50, expense_1=food, expense2=gas, etc... as well as $i, I just dont know how to add those variables to an array each time.
Right now with this code I'm getting
4
Array ( [] => ) Array ( [] => ) Array ( [] => ) Array ( [] => )
I apologize if I'm not being clear enough, but I am pretty inexperienced with PHP.
The syntax error you're getting is because you're using i instead of $i - however - that can be resolved easily.
What you're looking to do is "simple" and can be accomplished with string-concatenation. It looks like you're attempting this with $_GET['expense'] + i, but not quite correct.
To properly build the parameter name, you'll want something like $_GET['expense_' . $i], here you can see to concatenate strings you use the . operator - not the + one.
I'm going to switch your logic to use a for loop instead of a while loop for my example:
$values = array();
for ($i = $_GET['i']; $i > 0; $i--) {
$expense = $_GET['expense_' . $i];
$amount = $_GET['amount_' . $i];
$values[$expense] = $amount;
}
print_r($values);
This is following your original logic, but it will effectively reverse the variables (counting from $i down to 1). If you want to count up, you can change your for loop to:
$numVariables = $_GET['i'];
for ($index = 1; $index <= $numVariables; $index++) {
$expense = $_GET['expense_' . $index];
...
Or just serialize the array and pass it to the next site, where you unserialize the array
would be much easier ;)

PHP: push variable number of elements to associative array

A folder on my server holds a variable number of images. I'm working on a PHP script that is intended to retrieve the entire list of files there (a list of filenames) and create an associative array like so:
$list = array(1=>"image1.png", 2=>"image2.png", ...);
Basically, the list vector starts as empty and when a new image is found, its name has to be added to the list, with an incremented index: i=>"image[i].png"
How do I go about achieving this? Or in other words, how do I push a new element to my array?
I'm not sure why you are referring to this as an associative-array, but if you want to add somethign to an array, do it like this
$list = array();
$list[] = "image1.png";
$list[] = ....;
$list[] = "imagei.png";
If you want to push new item to your array, try with:
$list[] = "image" + ( count($list) + 1 ) + ".png";
If your items' indexes starts with 1, add +1 in the name as described above. If you are starting from 0 as it is natural behaviour, skip it and use as described below:
$list[] = "image" + count($list) + ".png";
So you are in fact re-implementing glob()?
$list = glob('/path/to/images/*.png');
If you are really want to reimplement it yourself
$i = 0;
$list = array();
while (file_exists('/path/to/image' . (++$i) . '.png'))
$list[$i] = "image$i.png";

PHP Array. Change every row data in table to a string then pass to array

I am trying to use to a loop to pull all rows from a table, and change every row to a string then pass to an array. Here is the script I am currently working on.
PHP:
function toggleLayers(){
$toggleArray = array($toggle);
for($i=0;$i<$group_layer_row;$i++){
$toggle=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray($toggle);
}
}
Right now it only returns a string without passing to the array. Been looking and can't seem to find anywhere or anyone that can explain this to me in plain english.
Hope you can help. Thanks
I have no idea what vars are what in your example, but if you wanted to loop through an array and change its contents, here's how i'd do it:
$myArray = array( 'thing', 'thing2' );
// the ampersand will pass by reference, i.e.
// the _Actual_ element in the array
foreach( $myArray as &$thing ){
$thing .= " - wat?!";
}
print_r( $myArray );
will give you
[0] =>
'thing - wat?!'
[1] =>
'thing2 - wat?!'
I think you will gonna change your code to something like this:
$toggleArray = array();
for ($i = 0; $i < $group_layer_row; $i++) {
// push your string onto the array
$toggleArray[] = mb_convert_encoding(mssql_result($rs_group_layer, $i, 0), "UTF-8", "SJIS") . "_" . mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1), "UTF-8", "SJIS");
}
return $toggleArray;

Replace non-specified array values with 0

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;

Categories