Put an array with foreach inside another array - php

I've just achieved a code where I make an array with foreach and in the same code I already have an existing array. What I want to do is to make only one array with those two results. Here is my code for the first array :
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
$res[] = $photos[$user];
}
else {
$res[] = '';
};
}
And here is my second array :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
)
);}
If you have any tips, any comment or even a question (if I wasn't clear enough for you), just ask me ! Thanks !
Edit :
What I want to make is an array of this type :
[{"name":"usera","publisher":"Jeana","image":"urla",""photouser","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","photouser","url2b"}]

You need to use the key you have in the first portion:
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
# Set the username--vvvevvvvv
foreach($restest as $username => $user) {
# Store the username as the key here for reference later
$res[$username] = (isset($photos[$user]))? $photos[$user] : '';
}
In this array, reference the username from the other array:
while($row = mysqli_fetch_array($result)){
$res2[] = array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
# Using the username as the key name, see if it $res has a saved value
"photouser" => (isset($res[$row['username']]))? $res[$row['username']] : false
);
}

I finally achieve what I wanted to do, by using a replacement technic :
With the foreach loop, I've created an array with the parameter profilepic, on the other array, I've created another parameter with a default value, then I replaced it.
My code : First my foreach loop :
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
array_push($res1, array(
"profilepic"=>$photos[$user]));
}
else {
array_push($res1, array(
"profilepic"=>'defaultvalue'));;
};
}
and then I changed :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
"profilepic"=>'defaultvalue'
)
);}
And finally I replaced it by :
$res = array_replace_recursive($res2,$res1);
So my final array with echo json_encode($res) is:
[{"name":"usera","publisher":"Jeana","image":"urla",""profilepic","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","profilepic","defaultvalue"}]

Related

php put multidimentional arrays into one big list from mysql database

I'm trying to create a single array of status id's and their names pulled from the database. My array needs to come out looking like this
$options = array("1" => "Active", "2" => "Inactive");
I've been trying to use array_push and array merge but it keeps going wrong. Here is what I have so far...
$allStatus = implode(',', array('1', '2'));
$statuses = $clCont->getAllRecords('*', '`status` WHERE idstatus IN ('.$allStatus.')');
$status = mysqli_fetch_assoc($statuses);
$statusOpt = array();
do
{
array_push($statusOpt[$status['idstatus']],$status['statusName']);
}
while ($status = mysqli_fetch_assoc($statuses));
$rows = mysqli_num_rows($statuses);
if($rows > 0)
{
mysqli_data_seek($statuses, 0);
$status = mysqli_fetch_assoc($statuses);
}
print_r($statusOpt);
Ok, let's try to modify your code:
$allStatus = implode(',', array('1', '2'));
$statuses = $clCont->getAllRecords('*', '`status` WHERE idstatus IN ('.$allStatus.')');
// you don't need to fetch first item.
// $status = mysqli_fetch_assoc($statuses);
// and use a do-while loop
// use just while:
$statusOpt = array();
while ($status = mysqli_fetch_assoc($statuses))
{
$id = $status['idstatus'];
// The first time you try to put a value in a
// $statusOpt[$status['idstatus']] it's not exists,
// so you should define it explicitly:
if (!isset($statusOpt[$id])) {
$statusOpt[$id] = array();
}
// after that it should be okay:
array_push($statusOpt[$id],$status['statusName']);
}
print_r($statusOpt);

Pushing two values from the database to one array

On line 6 I am pushing a value from the database to the array called $products. I would now like to give another value from the database ($row->image) to the same array which matches with $row->name.
Maybe it could make sense to use a two dimensional array but I don't know how to do this in this case.
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
if($result = $db->query("SELECT * FROM produkte WHERE $value = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push($products, $row->name);
}
}
}
else {
array_push($products, 'error');
}
}
The result should show me the name and the image of both values which belong together.
You could do this, assuming you already have your $row->name and $row->image matching logic sorted:
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image) );
}
You can try it like this:
$products = array();
foreach ( $_POST['selected_checkboxes'] as $value ) {
if ( $result = $db->query( "SELECT * FROM produkte WHERE $value = 1" ) ) {
while ( $row = $result->fetch_object() ) {
// if your name is unique you can do it like this,
// if not just take $row->id as index
if( isset( $products[$row->name] ) ) continue;
$products[$row->name] = array( "name" => $row->name, "image" => $row->image );
}
} else {
array_push( $products, 'error' );
}
}
// if you want to have plain digits as index you can get a reindexed array
$products = array_values( $products );
then you will get an array like that:
array(//$products
array(
"name" => "productname",
"image" => "productimage"
)
);
I think you can achieve that if you use a stdClass object.
$std = new stdClass();
$std->name = $row->name;
$std->image = $row->image;
array_push($products, $std);
Or you can change your sql query to
SELECT name, image FROM produkte WHERE $value = 1
and
array_push($products, $row);

Dynamic Array with PHP

Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;

Create a php array with keys and values from mysql query

I'm trying to store my mysql query in an array like this :
$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );
I've tried this but don't work like I need :
$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )
while ( $aRow = $sResult->fetch_assoc() )
{
$sInfo = $sResult->fetch_field();
// General output
$row_selectProduct[ $sInfo->name ] = $aRow;
}
$sResult->close();
Thx for help
EDIT :
Sorry for misunderstanding...
I'd like to name keys by the field name in database.
I try to reproduce this :
$result = array();
while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{
$row_array= array();
$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...
array_push($result,$row_array);
};
Using PDO connection functions, it's quite simple --
foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
echo $row['field_name1'].' '.$row['field_name2']; //etc...
}
Here's a good tutorial for PDO in PHP if you want more.
while ( $aRow = $sResult->fetch_assoc() )
{
foreach($aRow as $fieldname => $fieldvalue) {
$row_selectProduct[$fieldname] = $fieldvalue;
}
}
but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record
if you would like to have all results in one array you should:
$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
$results[] = $aRow;
}
if you know that there will be only one result you need only:
$result = $sResult->fetch_assoc();

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Categories