How to pas array in loop in php? - php

I am facing the problem is that I want to display all image by using array and loop,it is not showing all image ,it does show only one image.Here is my code
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths = array($img11[$i]);
}
}
here is in the database to extract out all image
the out put is showing only one image by using this code
<? echo $im_mouths[0].'11111'.'<br>';?>
<? echo $im_mouths[1].'222222'.'<br>';?>
<? echo $im_mouths[2].'333333'.'<br>';?>
I am not sure I'm doing correctly or not ,help me out this problem.
Thanks :)

It's only showing one image because you're re-writing $im_mouths each time you loop. You should change your loop to do the following:
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
We initialize $im_mouths as an array, then add each element to the array as an element: $im_mouths[] = ....

You need to simplify your code a bit.
Assuming you have a outer loop for retrieving data from database:
$im_mouths = array();
while ($objResult = $res->fetch()) {
if($objResult['Image_Type'] == '01') {
$im_mouths[] = $objResult['Image_Name'];
}
}
Now you have $im_mouths array of elements of image names, as many as you have in database. So as you see you don't need unnecessary inner for loop
Finally to see what you have in your $im_mouths array, you can print_r it:
print_r($im_mouths);

In your example, the variable $im_mouths should contain only the last image ( that is, 20140923jaobangsaen01.png ). Because you are using simple variable to store the image, so that the variable may contain last image while the program flow comes out from the for loop. So that the output of your example is correct. If you want to show each images means, you should use array variable to store all the images and display back to the required place. Rearrange the code like following,
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
Hope it will work fine for you.
Use can use foreach to display the images instead of using echo for each image.
$num = 1111; //if required
foreach ( $im_mouths as $value ) {
echo $value.$num;
$num += 1111;
}

Related

want to convert a key value pair to standard class object

Hi I need help [this is my table structure] and my current [JSON response is like this] and I want to convert this to [like this JSON response]
Can anybody give some idea or any related code so that I can make my JSON response like that.
*Note I can't create another table to store user images
First you don't need to concatenate your base_url to all images, you can use it separately in your front file, unless it must be there.
Second you don't need to store user_id to your image structure, because you have id right in your table's structure.
anyway you can do something like snippet below.
I hope it works fine :)
Edit:
It is easier to work with arrays in PHP so I convert my code to array version and if you need to use object first convert your object to array and after snippet you can convert it to object like (object) $data
foreach ($data as &$user) {
if(!empty($user['main_image'])) {
$user['main_image'] = $image_basepath . $user['main_image'];
}
$user['image'] = [];
for($i = 1; $i <= 6; $i++) {
$imgArr = [];
$img = $user['optnl_img' . $i];
unset($user['optnl_img' . $i]);
if(isset($img) && !empty($img)) {
$imgArr['id'] = $i;
$imgArr['user_id'] = $user['id'];
$imgArr['image'] = $image_basepath . $img;
}
$user['image'][] = $imgArr;
}
}

Get First And Last Data From conditioned foreach loop

Hello here i am with freaky problem,i wants the first data and last data from for-each loop. for that i have seen this answer. this would be really helpful but here my condition is really a little bit complex.
I have loop as following
<?php
$count = 0;
$length = count($myDataArray);
foreach ($myDataArray as $value) {
if($count >= 7)
{
//Some Data to Print
//this is first data for me
<tr >
<td><?=$myfinaldate?></td>
<td><?=$stockdata[1]?></td>
<td><?=$stockdata[2]?></td>
<td><?=$stockdata[3]?></td>
<td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
<td><?=$stockdata[5]?></td>
<td><?php echo $mydate; ?></td>
</tr>
<?php
}
$count++;
}
Now How can i Get First And Last Data from loop ?
I imagine you could use your length attribute.
As you have the total of your array, just check
myDataArray[0] and myDataArray[$length-1] ?
To fetch first and last value of the array use the below function :
$array = $myDataArray;
$array_values = array_values($myDataArray);
// get the first value in the array
print $array_values[0]; // prints 'first item'
// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'
You can use array_values to remove the keys of an array and replace them with indices. If you do this, you can access the specified fields directly. Like this you can check for your requirements on the array without looping over it, as shown in the if-conditions below:
$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
$wantedFields[] = $dataArrayValues[7];
if ($length > 8) {
$wantedFields[] = end($dataArrayValues);
}
}
Due to the conditions you will not print the 8th field twice in case it is the last field as well.
foreach ($wantedFields as $value) {
<tr>
... //Your previous code
</tr>
}

Delete the whole row from an array in php

How do I delete the whole line from an array? When the delete-button is pressed it should delete the whole line.
my array looks like that:
$liste[0][0] = email-user1
$liste[0][1]= password-user1
$liste[1][0] = email-user2
$liste[1][1]= password-user2
So if I delete the user one, the user2 should just take the place from user1(which should just disappear).
if (isset($_GET['delete'])){
$id=key($_GET['delete']);
for ($i = 0; $i < count($liste); $i++){
if ("$i"=="$id"){
unset($liste[$id][0]);
unset($liste[$id][1]);
unset($liste[$id][2]);
}
else{
}
}
update
I'm using array_splice($liste, $id, 1); now but everytime I try to save it to the file I get an error: implode(): Invalid arguments passed. For saving it to the file, I use the following function:
function saveDataToFile($fileName, $liste){
$file=fopen($fileName,"w");
for ($i = 0; $i < count($liste); $i++) {
$zArray=$liste[$i];
$zeile=implode("|", $zArray);
if(strlen($zeile) > 0){
$zeile=$zeile."\r\n";
fwrite($file, $zeile);
}
}
fclose($datei);
}
Try the below code:
$liste[0][0] = "email-user1";
$liste[0][1]= "password-user1";
$liste[1][0] = "email-user2";
$liste[1][1]= "password-user2";
$liste[2][0] = "email-user3";
$liste[2][1]= "password-user3";
unset($liste[1]); // say you want to delete this row
$new_arr = $liste;
unset($liste);
$i=0;
foreach($new_arr as $value){
$liste[$i] = $value;
$i++;
}
You can use array_splice() method:
array_splice($liste, $id, 1);
$liste[0][0], $liste[0][1] and $liste[0][2] are in real nothing else than a value array(value, value, value) (the inner array) which is assigned to $liste[0] (the outer array)
unsetting this (outer) array value $liste[0] is enough:
unset($liste[$id]);
If you care about the keys of this array (I see you loop from 0..n), you need to reindex your array using:
$liste = array_values($liste);
This will make your array behaving more like arrays normally do in other programming languages
Good practice is to use foreach instead of for. In this case you don't need to reindex:
for ($liste as $key=>$value){
if ("$key"=="$id"){
unset($liste[$key]);
}
But anyway you don't have to loop through an array just for finding a key. It's enough doing this:
if (isset($liste[$id])) { /* optional: check if the key exists */ }
unset($liste[$id]);

Variable inside of array not working?

I am trying to retreive some information outside of an array I have created inside of a loop.
If I hard code the array location things print out as expected. If I add the variable inside of the loop to print each array, I get nothing.
$num = 0;
foreach ( $repeatable_fields as $field ) {
$num++;
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[$num]);
}
Prints nothing. But if I replace $num with a value, say 1, things echo onto the screen.
But if I do:
$num = 0;
foreach ( $repeatable_fields as $field ) {
$num++;
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[1]);
}
This works as expected and prints out what I need. The reason I need to do this inside of a loop is because I have constructed multiple arrays $field_playback_format[1] and $field_playback_format[2] contain different values, but I need to retrieve them both inside the loop.
Am I not able to use a variable in this spot??
Array starts from 0, your script increment immediately the index and you have an error because the last loop try to get an element of array that doesn't exist because the index is +1 than the real value.
try this:
$num = 0;
foreach ( $repeatable_fields as $field ) {
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[$num]);
$num++;
}
Your second script works because you print an existing element. But if you try to print with a major index retrieve an error and you can't see the print_r

Incremented $_COOKIE[array] not working?

I am using a $_COOKIE[array] in order to save data for a single input. This input will only submit if the user entered the same value twice. For instance, if they submitted apple, then orange, then banana, then apple, the form would submit on the second appearance of "apple".
I read [this tutorial](
http://phpprogramming.wordpress.com/2007/03/06/php-cookies-tutorial-and-examples/).
for ($i = 1; $i < 10; $i++) {
if (!isset($_COOKIE[$i])) {
setcookie("query" . [$i],$query,time()+604800,"/");
break1;
}
}
foreach ($_COOKIE["query"] as $key => $value) {
echo "$key:$value";
}
I believe it might be a syntax error since I get:
Warning: Invalid argument supplied for foreach()
If you know a better way (can't be mySQL), then please let me know!
$_COOKIE["query"] is not an array, that's whats producing the error.
$_COOKIE['query'] can not store an array. This is also why you get an error when you try to use it in the foreach. You could serialize your array before saving it though. Something like this
$array = array();
for ($i = 1; $i < 10; $i++) {
$array[] = $i;
}
setcookie("query",urlencode(serialize($array)),time()+604800,"/");
$query = unserialize(urldecode($_COOKIE['query']));
foreach ($query as $key => $value) {
echo "$key:$value";
}
also have a look at this post update cookie value in php for the expalanation why the urlencode / urldecode is used

Categories