PHP $_Session array within array index number - php

I'm using a session array to store ingredient information. Each added ingredient has it's own array... as such
$_SESSION['ingredients'][] = array($_POST['ingredient'],$_POST['qty']);
Printing the array gives the following..
Array ( [0] => Array ( [0] => 1 [1] => 1 ) [1] => Array ( [0] => 1 [1] => 2 ) [2] => Array ( [0] => 1 [1] => 3 ) )
When pulling out the values of the array I am using the following...
$rows=$_SESSION['ingredients'];
if($rows){
foreach($rows as $row){
$sql = 'SELECT ingredient_name FROM ' . INGREDIENTS_TABLE . ' WHERE ingredient_id = '.$row[0];
$result = $db->sql_query($sql);
$ingredient = $db->sql_fetchrow($result);
$template->assign_block_vars('ingr_list', array(
'INGREDIENT' => $ingredient['ingredient_name'],
'QTY' => $row[1],
'IDENTITY' => ****$id****, <-----HERE
));
}
What I'm looking for is the $id to equal the key value of that particular $row. Do I need to individually search the array each time I want to find it's ID (ie within the loop) or is there an easier solution?
Thanks

I think you need:
foreach($rows as $id => $row){

Looks like you need just
'IDENTITY' => $row[0],

Related

php select a random array value within while loop and assign it to a variable

How can I get and assign a random array value from array inside a while loop to a variable?
Code
$stmt = $pdo->prepare("SELECT mem_id FROM members WHERE mem_id NOT IN (SELECT ref_referral FROM referrals)");
$stmt-> execute();
$rec = array();
while($f = $stmt->fetch()){
$rec[] = $f;
}
print_r($rec);
The above code returns this array
Array
(
[0] => Array
(
[mem_id] => 2
[0] => 2
)
[1] => Array
(
[mem_id] => 3
[0] => 3
)
[2] => Array
(
[mem_id] => 4
[0] => 4
)
)
Now if I want to take one value from either of 2,3,4 randomly and assign it to a variable say $randomValue = $randomValueFromArray, how can I do that?

Creating and pushing to arrays

I am trying to create an array(if it does not already exist) and then push values to it.
foreach($playlist->items as $item) {
$str = $item->snippet->title;
$id = $item->snippet->resourceId->videoId;
$substring = substr($str, 0, 5);
$substring = strtolower($substring);
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
}
I am iterating through data retrieved from a Youtube playlist, so I go through each item with foreach which holds a 'title' - the artist and an 'id' - the video Id . I substring each title and try to use this to group artists into specific arrays.
If an array already exists for that artist, I try to push the 'id' onto the end of that array. If an array does not exist, I create one and then push the 'id' onto that array.
At the end I try to push each artist array into the 'artists' array.
What I get when I print out $artists array is something like this
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
)
...
[543] => Array
(
[0] => Exa0CzlCb3Y
)
Every single $id is in it's own array when they should be grouped together based on $substring. e.g
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
[4] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
)
What am I not understanding?
Here is a simpler solution to your problem:
$artists = array();
foreach($playlist->items as $item) {
$artist = $item->snippet->artist; // however the artist name is fetched..
$id = $item->snippet->resourceId->videoId;
$artists[$artist][] = $id
}
This way, you don't need to check if an artist is already in the array, it will do that automatically and append the video id to the artist.
The $artists array will be assosiative, I don't think you can do it with a numeric array.
The array will look like this:
Array
(
['Jon Lajoie'] => Array
(
[0] => 1_YUrdjLyAU
[1] => lf3hflkap39
[2] => 1vt1455zzbe
[3] => 6dthg3drgjb
[4] => jfop3ifjf3p
)
['Lonely Island'] => Array
(
[0] => Gp8lDW2LUM0
[1] => 5he5hj67j7r
[2] => krt7tkktzk8
[3] => we54w4ggsrg
)
)
Use substring as array key and do following:
**Remove**
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
**Replace**
$artist[$substring][]=$id;

php mysqli result into an array not working as expected

I have a php /mysqli query and I want to populate an array with the results:
$query3 ="SELECT * FROM conditions";
$results = array();
if ($result = mysqli_query($conn, $query3)){
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
print_r($results);
Something is wrong here -its making arrays within arrays I think. (to be honest I am confused by this result)
How do I do this correctly!
Array (
[0] => Array ( [condition_id] => 1 [condition_name] => Epilepsy )
[1] => Array ( [condition_id] => 2 [condition_name] => ASD )
[2] => Array ( [condition_id] => 3 [condition_name] => BESD )
[3] => Array ( [condition_id] => 4 [condition_name] => HI )
[4] => Array ( [condition_id] => 5 [condition_name] => Medical )
[5] => Array ( ...
Thanks for all the help - now how should I create what I actually want which is one array with key=>value like this:
array (1=>epilepsy, 2=>ASd...) - the numbers refer to the primary key.
How do I populate an array from this query please?
Change your code as below :
while($row = mysqli_fetch_assoc($result))
{
$results[$row['condition_id']] = $row['condition_name'];
}
Move to PDO, Luke.
$results = $pdo->query("SELECT FROM conditions")->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($results);
Whoops! Is that all the code?

Merge multple arrays from one result into a single array in PHP

I'm really sorry to bug you, put I've got a problem that I've been trying to resolve for quite some time now. I've done some research and have found things like array_merge but it doesn't appear to help me.
Anyway, enough waffle. I have a result of a query that looks something like this:
Array
(
[0] => STRINGA
)
Array
(
[0] => STRINGA
[1] => STRINGB
)
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
)
Array
(
[0] => STRINGD
[1] => STRINGC
[2] => STRINGA
[3] => STRINGB
[4] => STRINGE
[5] => STRINGF
)
How can I combine the above into one array so that the result will look more like:
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
[3] => STRINGD
[4] => STRINGE
[5] => STRINGF
)
Duplicates in the original arrays can be ignored as I only need the string to be placed into the new array once.
Any help would be massively appreciated.
Thank you.
EDITED: This is the block of code that brings out the result from the database:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $splitrow) {
if(NULL != $splitrow) {
$therow = explode(';',$splitrow);
}
//print_r retrieves result shown above
print_r($therow);
}
}
$bigarray = array(
array (
0 => 'STRINGA',
),
array (
0 => 'STRINGA',
1 => 'STRINGB',
),
array(
0 => 'STRINGA',
1 => 'STRINGB',
2 => 'STRINGC',
)
);
$result = array_values(
array_unique(
array_merge( $bigarray[0], $bigarray[1], $bigarray[2] )
)
);
// array_merge will put all arrays together, including duplicates
// array_unique removes duplicates
// array_values will sort out the indexes in ascending order (1, 2, 3 etc...)
$bigarray = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $value){
if($value != NULL){
$therow = explode(';',$value);
foreach($therow as $key=>$values){
//push the value into the single array 'bigarray'
array_push($bigarray, $values);
}
}
}
}
//remove duplicates
$uniquearray = array_unique($bigarray);
//reset key values
$indexedarray = array_values($uniquearray);
print_r($indexedarray);
Thanks to all of those that helped, much appreciated!

PHP/MySQL: Recreate multidimensional array from existing array

I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.

Categories