MySQLi Multiple Queries, accessing second array - php

I have a multi-query MySQLi statement that uses multiple queries and when using var_dump brings back the following:
var_dump of array:
array(1) { ["company"]=> string(8) "ffr3e456" ["high_1"]=> string(8) "8.32465" }
array(2) { ["company"]=> string(8) "gg8751hw" ["high_2"]=> string(7) "7.66574" }
The code I am using to display the array in a PHP file picks up the first array (i.e. the content of high_1 information but not the second.
code
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
for ($p=1; $p<=2; $p++)
{
echo number_format($row["high_".$p],2);
The HTML output shows the data from the first array but not the second. I am sure I am overlooking something, any advice and feedback welcomed.

$C = array_merge($A, $B);
You can read more here: http://www.php.net/manual/de/function.array-merge.php

It would be helpful if you showed the SQL statement that returns the results.
Are the returned arrays in separate $row results?
In that case you need to iterate through each $row result, something like:
foreach($query->result() as $row)
{
for ($p=1; $p<=2; $p++)
{
echo number_format($row["novhigh_".$p],2);
}
}
On a side note: It looks like the key definition inside the arrays is not logical, why not have the same key value for the "novhigh" element?

Related

What is the correct syntax for detecting an empty 2D array in PHP?

What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:
if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
print_r($strengths[0][0]);
echo "<br>blah<br>";
print_r($sizes[0][0]);
}
Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):
In the picture you can see the array is also empty again.
It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.
What am I doing wrong?
Edit 1:
The code:
var_dump($strengths[0][0]);
var_dump($sizes[0][0]);
returns:
array(0) { }
array(0) { }
and the code:
var_dump($strengths[0]);
var_dump($sizes[0]);
returns:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
Edit 2:
This is my init:
$sizes[][] = array();
This is where data is set:
foreach($products as $product)
{
//product information
foreach($mods as $mod)
{
//mod information
//when array is empty $mods is empty
if ($modType == "SIZE")
{
$sizes[$si][0] = $modValue . $modValueSuffix;
$sizes[$si][1] = $modPrice;
$sizes[$si][2] = $modID;
$si++;
$strengthOrSize = true;
}
}
}
I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.
You can do this to detect if the sub array is empty:
$arr = [[]];
if (!count($arr[0])) {
// do stuff
}

Merge arrays with strings and delete repetitive values in PHP

From WP_Query I am dumping strings stored into separate arrays:
array(1) {
[0]=>
string(8) "Portugal"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(5) "Italy"
}
array(1) {
[0]=>
string(6) "Monaco"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(9) "Lithuania"
}
I am trying to merge those arrays into one array, delete repetitive strings like "Spain" and get the number of unique values.
I was trying to use array_merge():
$tester = array();
foreach($array_string as $value) {
array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
But without any decent results, error telling that <b>Warning</b>: array_merge(): Argument #2 is not an array Could someone tell where I am missing the point? Many thanks for all possible help, will be looking forward.
The code posted in the question is almost good. The intention is correct but you missed out a simple thing: you initialize $tester with an empty array and then never add something to it. In the end, it is still empty and array_unique() has nothing to do but return an empty array too.
The error is in the line:
array_merge($tester, $value);
array_merge() does not change the arrays passed to it as argument. It returns a new array that your code ignores (instead of saving it into $tester).
This is how your code should look like:
$tester = array();
foreach($array_string as $value) {
$tester = array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
Solution #2
You can use call_user_func_array() to invoke array_merge() and pass the values of $array_string as arguments. The returned array contains duplicates; passing it to array_unique() removes them:
$result = array_unique(call_user_func_array('array_merge', $array_string));
Solution #3
A simpler (and possibly faster) way to accomplish the same thing is to use array_column() to get the values into an array and then pass it to array_unique(), of course:
$result = array_unique(array_column($array_string, 0));
This solution works only with PHP 5.5 or newer (the array_column() function doesn't exist in older versions.)
To get the number of unique strings in the merged array you will have to set empty array before WP_Query
$tester = array();
Than inside while loop of WP_Query every string is put into separate array and pushed to $tester
foreach((array)$array_string as $key=>$value[0]) {
array_push($tester,$value);
}
Unique values in array $tester is found using array_unique() functions that should be placed after WP_Query while loop.
$unique_array_string = array_unique($tester, SORT_REGULAR);
$unique_string_number = sizeof($unique_array_string);
You will create an array and will take key of the array for cities names like spain..etc And it will give different cities name always...
$data= array();
$data1 = array("Portugal");
$data2 = array("Spain");
$data3 = array("Italy");
$data4 = array("Monaco");
$data5 = array("Spain");
$data6 = array("Lithuania");
$merge = array_merge($data1, $data2,$data3,$data4,$data5,$data6);
$data = array();
foreach($merge as $value) {
$data[$value] = $value;
}
echo '<pre>',print_r($data),'</pre>';

php - push array into an array -(pushing both key and the array)

I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.
All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
You can use array_merge function
$newrow = array_merge($newrow, $thumnail);
Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k

Problem with a while loop

My query does no return anything for my second index. It always sends me a message Notice: Undefined offset: 1. I tried doing with a for it is the same result, so I have read that my problem it is in the query, somebody told me let $stmt be null for freeing resources of my statement. I dont know what is wrong.
These are my methods. I dont know what to someone say use $database->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
Example: $arrayDirectory[] = {'user1', 'user2'};
It must echo 1 2 but just prints me 1
for($i=0;$i<sizeof($arrayDirectory;$i++){
$res[$i] = $obj->obtainID($arrayDirectory[$i]);
echo $res[$i];
}
This is my obtainID method:
public function obtainID($user){
$conexion = $this->objConexion->configuracion();
$query = "CALL sp_xxx('$user')";
$stmt = $conexion->prepare($query);
$stmt->execute();
$resultado = $stmt->fetchColumn();
return $resultado;
}
$stmi = null where?
For one,
$arrayDirectory[] = {'user1', 'user2'};
is a syntax error. { ... } does not work for arrays in PHP. Maybe it's just a typo and you're getting PHP confused with javascsript.
But the bigger issue is the []. That tells PHP to treat $arrayDirectory as an array (fine), but PUSH as a single value whatever you're assigning.
If your code was really:
$arrayDirectory[] = array('user1', 'user2');
This would create the following structure:
array(1) {
[0]=>
array(2) {
[0]=>
string(5) "user1"
[1]=>
string(5) "user2"
}
}
Note that it's a 2-level array. A top level single-element array at index [0]. That element at 0 contains ANOTHER array, which contains your two usernames.
You should have this instead:
$arrayDirectory = array('user1', 'user2');
$res = array();
foreach($arrayDirectory as $user) {
$res[] = $obj->obtainID($user);
}
first of all you are wrong with your function, you forgot to add the ending ')' for sizeof function,also arrays aren't defined with { } you should use array( ) instead.
and finally you are doing a bad practice over there;
you should not call a function in a loop (sizeof()), like this every time the loop goes through it will initiate sizeof() function and it will take some resource, since sizeof($object) won't change while using the loop, you should save it in a variable
$sizeofobject = sizeof($object);
and use that variable in your loop instead

PHP: Assigning values to a variable inside IF statement

I was wondering if i could assign values to a variable inside an IF statement. My code is as follows:
<?php
if ((count($newArray) = array("hello", "world")) == 0) {
// do something
}
?>
So basically i want assign the array to the $newArray variable, then count newArray and check to see if it is an empty array.
I know i can do this on several lines but just wondered if i could do it on one line
Try this:
if(count($newArray = array("Hello", "world")) == 0) {
....
}
I'd advice against this though, as it makes your code less readable. And highly illogical too as you know that the array in question contains two values. But perhaps you have something else in mind. :)
Yeah, you can, like so:
if(count($ary = array(1,2,3)))
Doing a var_dump of $ary gives:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Actually you don't need to use count inside the if statement, because an empty array is considered to be false in PHP. See PHP documentation.
So your code can look like this:
if (!$newArray = array("hello", "world")) {
echo "newArray is empty";
}

Categories