1

I have a table where multiple images are uploaded .. the fields in the table are

++++++++++++++++++++++++++
id,user_id,photo,position
++++++++++++++++++++++++++

There can be maximum 8 images against a user id.

Now if an user upload image in suppose 1 , 3 , 5 position

And when i have to return the array after fetching from the database

i will get the value for the 1 , 3 , 5 position but i have to return the array with all the position that is from 1 to 8

So as per the requiremnet position 1 will have the value of 1 from the database as there is value in the database but there is no value against position 2 so in the array the position 2 will be blank...

Basically the position that have value in database will hold the value from the database and those position that doesn't have values in database will be blank

positions are 1 2 3 4 5 6 7 8

How to do it in php?

Rahul
  • 159
  • 2
  • 15

3 Answers3

0

You can't get from table value that does not exists there. So write code like this

$Something = 'test';
$aFromTable = array (1=>$Something,3=>$Something,5=>$Something);

for ($i=1;$i<9;$i++)
{
    if (!isset($aFromTable[$i]))
        $aFromTable[$i] = $Something;
}

var_dump($aFromTable);

or like this

$Something = 'test';
$aStandard[1] =  null;
$aStandard[2] =  null;
$aStandard[3] =  null;
$aStandard[4] =  null;
$aStandard[5] =  null;
$aStandard[6] =  null;
$aStandard[7] =  null;
$aStandard[8] =  null;
$aFromTable = array (1=>$Something,3=>$Something,5=>$Something);


$aFromTable = $aFromTable + $aStandard;
var_dump($aFromTable);
venoel
  • 463
  • 3
  • 13
0

select an array with position as keys of array for example..

$image[position] = image_name;

Code

$image[1] = image1;
$image[3] = $image3;
$image[5] = $image5;

Now run a for loop as follows

for($i=0;$i<8;$i++){
    if(!isset($image[$i])) $image[$i] = '';
}

You got the result what you want as $image array;

GYaN
  • 2,327
  • 4
  • 19
  • 39
0
<?php
$rows = [
    ['foo.jpg', 8],
    ['bar.jpg', 4],
    ['baz.jpg', 1]
];

$positions = array_fill(1, 8, null);

foreach($rows as $row) {
    $positions[$row[1]] = $row[0];
}

var_export($positions);

Output:

array (
  1 => 'baz.jpg',
  2 => NULL,
  3 => NULL,
  4 => 'bar.jpg',
  5 => NULL,
  6 => NULL,
  7 => NULL,
  8 => 'foo.jpg',
)

Example SQL used to produce a rows array:

SELECT photo, position FROM photo_table WHERE user_id = 3
Progrock
  • 7,373
  • 1
  • 19
  • 25