Grabbing specific values from a multi-dimensional array in PHP - php

I'm new to programming and I'm tackling arrays. I thought I had multi-dimensional arrays figured out but I guess I don't. Here's the code I'm working on:
$loopcounter = 0;
while ($myrow = mysql_fetch_array($results)) {
//...other stuff happens...
$allminmax[$loopcounter][] = array("$myrow[3]","$currentcoltype","$tempmin","$tempmax");
$loopcounter++;
}
This chunk of code is supposed to create an array of four values ($myrow[3], currentcoltype, tempmin, tempmax) and insert it into another array every time the loop goes through. When I do this:
echo implode($allminmax);
I get:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Do I need to implode each array before it goes into the master array? I really want to be able to do something like $allminmax[0][4] and get the $tempmax for the first row. When I try this now nothing happens. Thanks -- any help is appreciated!

It looks like you should either use [$loopcounter] or [], but not both. You also should drop the quotes. They're unnecessary and in the case of "$myrow[3]" they interfere with the variable interpolation.
$allminmax[] = array($myrow[3], $currentcoltype, $tempmin, $tempmax);
By the way, arrays are zero-indexed, so to get $tempmax for the first row it'd be $allminmax[0][3] not $allminmax[0][4].
Also, a better way to display the contents of your array is with print_r or var_dump. These will display arrays within arrays while a simple echo will not.
var_dump($allminmax);

Related

How to show the values with explode if one value it´s array

I have question about explode, because i have string with differents values separated by ",", and some values take from $_POST Array, for example multiselect fields, but i don´t know if i writte right this in PHP
Take Values- in this case $_POST['opt']['selection'] it´s array :
$values="house,car,colors,".$_POST['opt']['selection']."";
As you can see in the other point in the string "$values", the different values are separated by "," and now i go to explode these values
$exp_values=explode(",",$values);
Now i try show all values :
foreach($exp_values as $exp_values_end)
{
if(is_array($exp_values_end))
{
/// In this point must show values from array for process, and aplicate other time foreach, but don´t show nothing
}
else
{
$exp_values_end
}
}
I try different ways for get values from arrays when use with explode, but finally get nothing, by this, my questin it´s about, if it´s possible do this and how i can use explode when some values really are arrays, how in the case i show in this post, thank´s in advanced
Thank´s
First you need to transform your string into array. You can create a function convertStrToArray() who's retuning arguments as array. With ...$listString notation, you can add all your string variables.
I havn't tested it but you can try and debug :)
function convertStrToArray(...$listString)
{
return func_get_args();
}
$list = convertStrToArray('house', 'car', 'colors', $_POST['opt']['selection']);

how can I keep looping through an array until every element is moved to another array?

I'm newby in PHP but I allready have a difficult question.
I have an array which is like this:
$test = array("00000","00001","00011","00111","00101","00110","00110", etc (so it is unordered...)
now:
I'd like to check the first position with the second. if the Levensthein is <=1 then that value should stay in place and if it is not it should either.
move to the last position in the array...
or move to another array (i don't know what is best)
after that, the next 2 values should be checked with eachother...
so how can you keep looping through an array?
The easiest way to keep looping over an array until it is empty is to have two loops: one that loops until the array is empty and inside it one that loops over each element remaining in the array.
Just make sure that your code ensures that the array will go empty eventually or it'll be trapped in an infinite loop.
while(count($array)) {
foreach( $array as $element ) {
// your code goes here
}
}

Fill a php array with the content of other php arrays

I've been searching for a while now to accomplish my question, so I decided to ask it here.
My problem.
I've filled 2 arrays with content from a database like this:
$query = "SELECT table_1, table_2 FROM questions";
// Execute query or trow an error
$results = mysqli_query($conn, $query) or die(mysql_error());
$resulttablet1= array();
$resulttablet2= array();
while($row = mysqli_fetch_array($results))
{
// Add the right questions to the array
$resulttablet1[] = $row['table_1'];
$resulttablet2[] = $row['table_2'];
}
So I've now got 2 arrays, each filled with the content of one table. This is all working fine. Now I want to put those two arrays into one array so it acts like one big array.
Something like this:
$newarray = array();
$newarray[$resulttablet1, $resulttablet2];
or
$newarray = array($resulttablet1,
$resulttablet2);
Then I want to echo $newarray and show all the elements of the other two arrays.
I know I can echo both arrays separately, but this is not possible for the goal I'm trying to accomplish.
Thanks in advance.
Edit
I realise my question isn't clear enough, I'll try to explain it a bit better.
On top of my question I want to show the the content of both arrays one by one on button click. That's what I'm doing at the moment like this:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
// I use $value to echo the right element out of the array.
echo "<li>$resulttablet1[$value]</li>";
Everytime the button is clicked ajax loads the php file and the value is increased so the next question is loaded.
I want to do the same thing but now with an array which has multiple arrays inside of it.
array_merge doesn't do the trick I think, cause print_r($result); gives me all the content of the array.
I hope my question is a little bit more clear now.
I found the answer, thanks to someone who removed his answer already.
array_merge did the trick after all, I don't know what I did wrong the first time but now I can echo it just fine.
Here is how it works:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
$newarray = array_merge($resulttablet1, $resulttablet2);
echo "<li>$newarray[$value]</li>";
Hope someone will find this useful, if not ask for more info :)

alphanumeric sorting with php and preg_match

I have an array called $itemArray[] that contains a set of strings, such as:
myItem_1,
myItem_2,
myItem_3,
myItem_4,
anotherName_1,
anotherName_2,
anotherName_3,
anotherName_4
I also have the following code that goes through the array and filters out the ones that contain 'myItem'.
The loop works, however, it returns results in varied order. Is there a way to sort the result of the array so
that it lists them alphanumerically?
foreach($itemArray as $item) {
if (preg_match('/myItem/',$item))
echo '$item';
}
I don't have much experience with php and would definitely appreciate the help! Thank you!
PHP supports lots of ways to sort arrays, see how they work here. You could run it as asort($itemArray).
The right way to solve this is by sorting the array prior to outputting it. Something along the lines of:
asort($itemArray);
foreach($itemArray as $item) {
if (preg_match('/myItem/',$item))
array[index++] = $item;
}

PHP scope question

I'm trying to look through an array of records (staff members), in this loop, I call a function which returns another array of records (appointments for each staff member).
foreach($staffmembers as $staffmember)
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
This is working OK, however, later on in the script, I need to loop through the records again, this time making use of the appointment arrays, however they are unavailable.
foreach ($staffmembers as $staffmember)
{
//do some other stuff
//print_r($staffmember['appointments'] no longer does anything
}
Normally, I would perform the function from the first loop, within the second, however this loop is already nested within two others, which would cause the same sql query to be run 168 times.
Can anyone suggest a workaround?
Any advice would be greatly appreciated.
Thanks
foreach iterates over a copy of the array. If you want to change the value, you need to reference it:
foreach($staffmembers as &$staffmember) // <-- note the &
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
From the documentation:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
and
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

Categories