Having trouble building single array from while loop in PHP - php

I am trying to build an array from entries in a MySQL database. I have connected to the database just fine, and I have a foreach loop which pulls the entries from the database based on the quantity of items like so:
$totalMarkers = count($results);
foreach($results as $result){
$gpsLats[] = $result->gpslat;
$gpsLongs[] = $result->gpslong;
}
I then need to take these entries and run them through a while loop to attempt to build my array:
$it = 0;
while ($it < $totalMarkers) {
$incr = $it++;
$myLatitudes = $gpsLats[$incr];
$myLongitudes = $gpsLongs[$incr];
$items = array($myLatitudes,$myLongitudes);
print_r($items);
}
The problem is that the output looks something like this:
Array ( [0] => 54.8607 [1] => -32.4135 )
Array ( [0] => 39.8460 [1] => -87.4166 )
Array ( [0] => 78.8403 [1] => -95.4156 )
Really what I need is for all the entries to be contained in one array statement. I have a good feeling that I am overcomplicating this, but I need a nudge in the right direction. Thanks for your time in looking into this.

You forgot the array 'append' operation:
$items[] = array($myLatitudes,$myLongitudes);
^^--- missing
Without the [], you're simply creating a two-item array and overwriting it on every loop iteration.

Related

How to put keys in array?

I am scrapping details from a certain website. Then I want to parse HTML into a PHP array.
I want to display the array like this. I need to add key so that I can determine easily what data I want to use in the future.
[info] => Array
(
[0] => info1
[1] => info2
)
Here is my code:
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$hometps[] = $home->plaintext;
}
print_r(array_fill_keys($hk,$hometps));
But output will show me this:
Array
(
[info] => Array
(
[0] => info1
[1] => info2
)
)
Array element cannot stand on its own. Considering you want info as an index, it has to be a part of an array.
If you want the list of info available then assign them to $info variable and when you print_r($info), like this:
$info = array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$info[] = $home->plaintext;
}
print_r($info);
And you will get:
Array
(
[0] => info1
[1] => info2
)
Looks like you might be trying to rename the representation value in the array also known as the 'key' I guess. I recommend doing that directly to the output of the html while going into the foreach. That should solve your issue. It would look something like this(original example at bottom):
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $hk => $home) {
$hometps[] = $home->plaintext;
}
print_r($hometps);
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to the $key variable on each iteration.
PHP.net:foreach
I think everybody is confused about the issue and question here. The following will give you an array named $info, which will hold the returned values of the foreach loop:
$info = Array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
array_push($info,$home->plaintext);
}
print_r($info);
This will output:
Array (
[0] => info1
[1] => info2
)
Hope this was what you were trying to achieve.

php - count elements in array

I am trying to count elements in an array, but it doens't work as intended:
I have a while loop, which loops through my user table:
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
print_r($new_array);
$outcome = $rentedrefs->_paying($new_array);
}
The print_r($new_array); gives me:
Array
(
[0] => 90427
)
Array
(
[0] => 90428
)
Array
(
[0] => 90429
)
Array
(
[0] => 90430
)
Array
(
[0] => 90431
)
Array
(
[0] => 90432
)
Array
(
[0] => 90433
)
Array
(
[0] => 90434
)
Array
(
[0] => 90435
)
Array
(
[0] => 90436
)
Inside the _paying function, I count the number of values from the array:
function _paying($referrals_array){
echo count($referrals_array);
}
The problem is, that the above count($referrals_array); just gives me: 1, when it should be 10
What am I doing wrong?
You create a new array at each step of the loop. Instead it should be written like this:
$new_array = array();
while($refsData=$refs->fetch()){
$new_array[] = $refsData['id'];
// print_r($new_array);
}
$outcome = $rentedrefs->_paying($new_array);
Note that I moved the _paying call outside the loop, as it seems to be the aggregating function. If not, you'd most probably make it process $refsData['id'] instead - not the whole array.
As a sidenote, I'd strongly recommend using fetchAll() method (instead of fetch when you need to fill a collection with results of a query. It'll be trivial to count the number of the resulting array.
It works properly, in each circulation of loop you have one array, so in first you have:
Array
(
[0] => 90427
)
in 2nd:
Array
(
[0] => 90428
)
and so on.
It should work properly:
var $count = 0;
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
$count += count($new_array);
$outcome = $rentedrefs->_paying($new_array);
}
You are creating $new_array as a new array with the single element $refsData['id']. The count of 1 is therefore correct.
To get the number of results, either use a COUNT(*) select to ask your sql server, or add a counter to your loop, like this:
$entries = 0;
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
print_r($new_array);
$entries++;
$outcome = $rentedrefs->_paying($new_array);
}
echo $entries;
You are not adding elements to an array, but creating a new array each iteration. To add elements, just do:
$new_array[] = $refsData['id'];

PHP foreach not returning the string i need

i got this little problem with an array. I have products that belong to one or more categories and i need to display them as an array. First, this is my code to get categories from product 1 only:
$prod = $this->getDi()->productTable->load(1);
$prod_cat = $prod->getCategories();
print_r($prod_cat);
This will output this:
Array ( [0] => 1 )
So far so good. However, i need to do the same for all the products in existence at once. So im doing this:
$act_prod = Array ( 0 => 1 ); //array can contain more than one product, as of now it only contains one
foreach ($act_prod as $act) {
$cat = $this->getDi()->productTable->load($act);
$active_cat[$act] = $cat->getCategories();
}
print_r($active_cat);
But this will output:
Array ( [1] => Array ( [0] => 1 ) )
which is not what i need but this instead:
Array ( [0] => 1 )
I cant figure out whats wrong. Could you please give me a hint?
Thank you.
$cat->getCategories() returns an array, you add an array to another array each iteration, so is the result.
If you want to merge all the categories to a array, use array_merge instead:
$active_cat = array();
foreach ($act_prod as $act) {
$cat = $this->getDi()->productTable->load($act);
$active_cat = array_merge($active_cat, $cat->getCategories());
}
And side note, it's quite not efficient do such loop, you may get all the categories with just one query.

Show Can I pull Each Of These Out Of An Array?

I am having trouble pulling elements out of this multi-dimensional array?
Here is my code below:
$ShowTables = $Con->prepare("SHOW TABLES");
$ShowTables->execute();
$ShowTResults = $ShowTables->fetchAll();
If I print_r($ShowTResults); I get this multi-dimensional array:
Array (
[0] => Array ( [Tables_in_alltables] => userinformation [0] => userinformation )
[1] => Array ( [Tables_in_alltables] => users [0] => users )
)
Foreach new table is loaded it adds another dimension of the array. I want to pull each of the table names, out of the multi-dimensional array into a new array which I can use for future plans.
Would anyone have any ideas?
I have tried 1 foreach Loop; but this served no justice.
You want to fetch all results of the first column in form of an array:
$ShowTResults = $Con->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($ShowTResults);
This gives you:
Array (
[0] => userinformation
[1] => users
)
Which I think is what you're looking for.
Another variant (a bit more complicated, but fitting for similar but little different cases) is to fetch the results as function (PDO::FETCH_FUNC) and directly map the result:
$ShowTResults = $ShowTables->fetchAll(PDO::FETCH_FUNC, function($table) {
return $table;
});
A Solution I tried: Perhaps not as other will do, which is in full respect. But Here is mine:
$DatabaseTables = array();
foreach($ShowTResults AS $ShowTResult)
{
foreach ($ShowTResult AS $ShowT)
{
$DatabaseTables[] = $ShowT;
}
}
$DatabaseTables = array_unique($DatabaseTables); //Deletes Duplicates in Array
unset($ShowTResult);
unset($ShowT); // Free up these variables
print_r($DatabaseTables);

Counting distinct values in a multidimensional array

I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}

Categories