Using the nth item in a php array - php

I have created an array, as follows:
$results = array();
do {
$results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));
print_r($results);
This prints out the array like this:
Array (
[0] => Array (
[productName] => product1
)
[1] => Array (
[productName] => product2
)
[2] => Array (
[productName] => product3
)
I want to now use say the second item in the array in another mysql query.
But I cannot define it. I have tried
$results[1];
but this does not work.
So in effect, if I echo the second item, it would print 'product2'.

You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php
You are using a nested array, so you have the access it like this:
echo $results[1]['productName'];
Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].
In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.
while ($row_products = mysql_fetch_assoc($products)) {
$results[] = $row_products;
}

try this :
echo $results[1]['productName'] ;
$results[1] is an array, If you want see the array print_r($results[1]);

Related

selecting value of particular index with PHP foreach

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

new array not appearing after foreach

I have the following code, as you can see I would like to create a new array inside the foreach. Even though its adding perfectly fine WITHIN the loop , all seems to be forgotten once the loop is finished.
foreach ($results as $result) {
$result['categories'] = array();
echo '<pre>';print_r($result);echo '</pre>';
}
echo '<pre>';print_r($results);echo '</pre>';
Result of first print_r
Array
(
[word_two_id] => 2
[categories] => Array
(
)
)
Array
(
[word_two_id] => 3
[categories] => Array
(
)
)
Array
(
[word_two_id] => 5
[categories] => Array
(
)
)
Array
(
[word_two_id] => 12
[categories] => Array
(
)
)
Result of second print_r
Array
(
[0] => Array
(
[word_two_id] => 2
)
[1] => Array
(
[word_two_id] => 3
)
[2] => Array
(
[word_two_id] => 5
)
[3] => Array
(
[word_two_id] => 12
)
)
$result in the foreach is going to be overwritten in your loop on every iteration. e.g. every time the loop rolls around, a NEW $result is created, destroying any modifications you'd done in the previous iteration.
You need to refer to the original array instead:
foreach ($results as $key => $result) {
^^^^^^^
$results[$key]['categories'] = array();
^^^^^^^
Note the modifications. You may be tempted to use something like
foreach($results as &$result)
^---
which would have worked, but also leave $result a reference pointing somewhere inside your $results array. Re-using $result for other purposes later on in the code would then be fiddling with your array, leading to very-hard-to-track bugs.
In PHP, the foreach loop operates on a shallow copy of the array, meaning that changes to the elements of the array won't propagate outside of that loop.
To pass the array elements by reference instead of by value, you put an ampersand (&) before the name of the element variable, like so:
foreach ($results as &$result) {
$result['categories'] = array();
echo '<pre>';print_r($result);echo '</pre>';
}
This way, any changes to the array elements are instead performed on a reference to that element in the original array.
Marc B made a good point in his answer regarding a consequence of using this method. After the foreach loop is done and the code continues, the variable $result will continue to exist as a reference to the last element in the array. So, you shouldn't reuse the $result variable without removing its reference first:
unset($result);
You will need the key too
try this
foreach ($results as $key=>$result) {
$result['categories'] = array();
$results[$key] = $result;
}
echo '<pre>';print_r($results);echo '</pre>';

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'];

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

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