Making a dynamic array - php

THE ANSWER THAT WORKED FOR ME BASED ON AN ANSWER GIVEN
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
$array = array_merge($array, $push);
}
So I'm trying to display tags from my data base and make links out of them like this:
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
$array = array();
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_push($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
<? }
?>
However all I get back is
Array
Where I should be having at least three lines as was previously produced by
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
while($post = mysql_fetch_array($tags)) {
$array = explode(',', $post['tags']);
foreach ($array as $value) {?>
<? echo $value?>
<? }
}
?>
The code being called looks like this:
tag1, tag2, tag3
Tried
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_merge($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
now foreach doesn't return a value

Use array_merge(), because array_push() will push the output of explode(), which is an array, as a whole to the array in the first argument, creating a jagged array.
As for your edit, this works:
$array = array_merge($array, $push);
foreach ($array as $value)
{
echo '' . $value . '';
}
Please note that array_merge() (contrary to array_push(), gotta love the consistency) does not alter the array passed as its first argument, so you'll have to store the return value which I do on the first line ($array = ...).
While outputting to HTML, you also might want to put a $value = htmlentities(trim($value)); in the foreach loop.

Related

How to remove duplicate value in loop not using array

I want to remove or hide duplicate values in loop , It's not array.
You can see in picture 1/3, & 2/2 is repeating so I want only once using loop. It's not return any array it's simple data so we can't use array_unique
$i=1;
$result = array();
foreach ($boxes as $key => $value) {
foreach ($result as $k => $val) {
echo $i."/".count($value).'</br>';
}
$i++;
}
Expected Output
REG-Pre-Cut Short 1/3
REG-Pre-Cut Long -
PREM-Pre-Cut Short -
PREM-Pre-Cut Short 2/2
PREM-Pre-Cut Long -
Try something like this.
First you create an array in the expected format.
Then use array_unique to remove duplicates.
Then you print out the array.
$i=1;
$result = array();
$outputResult = array();
foreach ($boxes as $key => $value) {
foreach ($result as $k => $val) {
$outputResult[] = $i."/".count($value).'</br>';
}
$i++;
}
$outputResult = array_unique($outputResult);
foreach ($outputResult as $result) {
echo $result;
}

Get unique value from an array php

I want to display only unique strings and I have this code:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
$array = array_unique($array);
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
echo '' . $value . '<br>';
}
}
I have put an array_unique like this:
$array = array_unique($array);
But it returns this:
word-word
word
word2
word3
word-word
It doesn't print only unique values. What is wrong?
Think the problem is because the strings are being processed after the array_unique operation rather than before it. Try the following instead:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
}
$array = array_unique($array);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
}
I have resolved, i will post code may be will be good for someone!
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $key => $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
$alltags[]=$value;
}
}
$array=array_unique($alltags);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
Explode your string.
Trim outer spaces from each element.
Replace inner spaces with hyphen in each element.
Only keep non-empty elements.
Only keep unique elements (using double array_flip).
Display results.
Code: (Demo)
while($rez=$result->fetch_assoc()) {
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){$clean[]=$v;} // retain non-empty values
}
$clean=array_flip(array_flip($clean)); // double flip is faster than array_unique
foreach($clean as $v){
echo "$v<br>";
}
}
Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch. This will remove the potentially unnecessary trailing from final element:
Code:
$rez['tags']=' , word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){
$clean[]="$v"; // prep non-empty values for display
}
}
echo implode("<br>",array_unique($clean));
Output:
word<br>
word-word<br>
word2<br>
word3

using foreach multiple times

How can I use foreach multiple times?
<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>
I want to use the first foreach to show the data tables:
<?php foreach($query as $row){
echo $row['beras'];
}?>
Then I want to use the second foreach for chart:
<?php foreach($query as $row){
echo $row['telur'];
}?>
However, this foreach works only once.
You can do this:
1) save your data to an array.
foreach($query as $row){
$data[]= $row;
}
2) use your array in every loop you want as many time you want
foreach($data as $row){
echo $row['beras'];
}
foreach($data as $row){
echo $row['telur'];
}
Use foreach only once and store all values you need, like this:
<?php
$beras_array = array();
$telur_array = array();
foreach($query as $row){
$beras_array[] = $row['beras'];
$telur_array[] = $row['telur'];
}
//you can use `for` explained later instead of two `foreach`
foreach($beras_array as $b){
echo $b;
}
foreach($telur_array as $t){
echo $t;
}
//With this method you can also use only one for instead of two foreach
$limit = count($beras_array);
for($i=0; $i<$limit; $i++){
echo $beras_array[$i];
echo $telur_array[$i];
}
?>
I hope it helps

Basic implode foreach

I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Why are you assigning $elements = $array; and then never using $elements?
Also you don't need to loop (foreach) to implode an array.
Try this:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
// this array_push() function adds $value to the end of $new_array.
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Here is the documentation on implode()
You can play around and test the above code here.
Also next time, add the tag php, otherwise our codes won't get color syntax.

Copy values into another array

I have the following code:
foreach ($row as $item) {
foreach($item as $key) {
echo "<pre>";
print_r($key);
echo "</pre>";
}
}
I am trying to copy the keys ($key) into another array for further processing. How can i do this?
define some variable as array $array = array(); and just push the keys in with array_push($array, $key);
$array = array();
foreach ($row as $item) {
foreach($item as $key) {
array_push($array, $key);
}
}
$aNew = array();
foreach($row as $item) {
foreach($item as $key) {
$aNew[] = $key;
}
}
But; why would you do this? You can also just perform your commands / processing inside the second foreach().
If you want to get all keys of an array you may use
array_keys()
instead. Also, if each of your rows has the same keys in your second foreach loop, you may break both of the loops after getting all the keys from the first row.
Just use array_keys()
$a = array();
$array_of_keys = array_keys( $a );

Categories