SELECT array from mysql table and print - php

I have a column in my table that contain an array like:
1,4,2,8,4,5,7
How to select these numbers and print them separately?
Item: 1
Item: 4
Item: 2
Item: 8
Item: 4
Item: 5
Item: 7
What I have tried:
$result = mysql_query('SELECT * FROM test');
$arr = array();
while(($row = mysql_fetch_array($result))) {
$arr = array_merge($arr , explode(',', $row['item']));
echo "Item: " . $arr . "<br>";
}
Result:
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Can anyone help me?

Your biggest problem is trying to echo the whole array at once rather than echoing an index of the array at a time.
Unless you plan on using all the rows again after the while loop, you don't need the array_merge so take that out. What you need is a foreach inside the while loop to loop through the array created by explode.
while(($row = mysql_fetch_array($result)))
{
$arr = explode(',', $row['item']);
foreach ($arr as $key => $value)
{
echo "Item [$key]: " . $value . "<br>";
}
}
(And you really should switch off of mysql_ to PDO or mysqli_ since mysql_ is deprecated.)

try:
$arr = explode(',', $row['item']);
foreach($arr as $single){
echo "item: $single";
}

You are almost there. I hope this gives the result you expect. In your question it is not quite clear how exactly the data is stored.
If all the data is in one row, this will do it:
$result = mysql_query('SELECT item FROM test');
$arr = array();
$row = mysql_fetch_array($result);
$arr = explode(',', $row['item']);
foreach ($arr as $item) {
echo "Item: " . $item . "<br>";
}

Related

How to split array in php with 2 strings?

How to split array with , in 2 parts so that that can be used as 2 strings in php?
I am getting this kind of array you can view image with this list.
I want to split this array to post id and title in separate columns.
<li id="recordsArray_'.$value['id'].','.$value['title'].'"></li>
Give a try with below code if it works for you
$arr = array('1,test1','2,test2','3,test3');
foreach($arr as $ar){
$res = explode(',', $ar);
$id = $res[0];
$title = $res[1];
echo 'id-'.$id;
echo ' title-'.$title;
echo '<br>';
}
If you want to separate array into two string, you can use explode like this short code:
$item = '4,test';
$var = explode(',', $item);
echo $var;
and for loop array, you can use
$array = array(YOUR_ARRAY);
foreach($array as $item){
$var = explode(',', $item);
echo $var;
}
Update 1:
You can use a simple array like below code:
$array = array(4, 'salar');
and use a code like this:
$array = array(4, 'salar');
foreach ($array as $item) {
dump(explode(',', $item));
}

Combine 2 Arrays In Foreach in PHP

I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array

PHP: Associate array index name in a foreach loop

I can get the index number from a foreach loop by doing the following.
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// gives me "1: $row etc
}
If my array is associative is there away to get the associative name instead of the index number into my loop?
Actually you allready did it:
$associativeArray = array(
'First' => 1,
'Second' => 2,
'Third' => 3,
);
foreach ($associativeArray as $index => $value) {
echo $index . ": " . $value;
}
// First: 1
// Second: 2
// Third: 3
<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// $index will be hi and foo
}
?>
PHP arrays ARE associative where regular arrays just have integers as keys.
The PHP documentation actually mentions this in the first sentence: http://php.net/manual/en/language.types.array.php
An array in PHP is actually an ordered map..
PHP doesn't have arrays, it has maps/dictionaries that are called arrays but they are not arrays like in other languages.

PHP foreach loop not reading values from array

I have simple PHP array with data from checkbox. I need add values into array and then insert data into database. It works but foreach not infringement parameter.
So i testing with increment:
$arr = array();
array_push($arr, $_POST['chbox']);
and it looks like 123,125 in array (two elements)
Next step is to return number of elements (or values in next step):
$id=0;
foreach( $arr as $row)
{
$id++;
};
and returns $id=1;
if i'm trying read values:
foreach( $arr as $row)
{
$row[$id]
$id++;
};
Return only 123
If you are doing a foreach, $row is the value already.
foreach($arr as $row) {
echo $row;
$id++;
}
In your foreach() loop, $row is just one array value. Not the array. Replace with $arr should solve.
$id = 0;
foreach( $arr as $row ){
echo $arr[$id];
$id++;
}
echo 'Total items: ' . $id; // OR count( $arr );
$arr =array(123,125);
foreach($arr as $arrr):
echo $arrr.',';
endforeach;
Output will be:
123,125,
Just try following
foreach($arr as $row){
echo $row;
};
Edit 1:
Better use var_dump($_POST["chkbox"]) or print_r($_POST["chkbox"]) to see the array you are getting. Then it will be easier for you to decide how to get data.

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Categories