how to loop array from given array in php [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 20 days ago.
Improve this question
I've array like this in php I want to loop this array inside div elements in php:
`Array
(
[item] => Array
(
[0] => Masaladosa
[1] => Zingafry
[2] => Idli
[3] => Tandoori Baby Corn Mushroom
[4] => Bharwan Aloo
)
[qty] => Array
(
[0] => 2
[1] => 4
[2] => 2
[3] => 2
[4] => 2
)
[price] => Array
(
[0] => 320
[1] => 800
[2] => 70
[3] => 560
[4] => 560
)
)`
I want to use loop this array inside following div:
<div class="row mt-4 mx-1">
<div class="col-6 text-start item-listmenu">
<p class="bill-order">Masala dosa</p>
</div>
<div class="col-2 text-start">
<p class="bill-order">2</p>
</div>
<div class="col-4 text-end">
<p class="bill-order"><span>₹</span>320</p>
</div>
</div>
and so on.

I know this isn't an answer per se but I don't know how in a comment to write the layout of the array.
And so, all that to say that the organization of your data in arrays is very strange. Can't you have a array of this type instead...? It would be much more consistent and easier to navigate to view the layers.
Array
(
[0] => Array
(
[item] => Masaladosa
[qty] => 2
[price] => 320
)
[1] => Array
(
[item] => Zingafry
[qty] => 4
[price] => 800
)
)
...
// An example to browse this array (nammed list)
foreach($list as $key => $val)
{
echo "<br />".$key." - ".$val["item"]." - ".$val["qty"]." - ".$val["price"];
}

The easiest solution: Split the array into three (one for Item, Qty, and Price), and use a foreach with a named index variable. This works as long as the numerical index is consistent across all three nested arrays:
<?php
$itemArray = $array['item'];
$qtyArray = $array['qty'];
$priceArray = $array['price'];
foreach($itemArray as $key => $item) {
var_dump($item, $qtyArray[$key], $priceArray[$key]); // Note that $item === $itemArray[$key]
}

Related

PHP: how to compare value of one array with value to other array in the loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Trying to implement the following functionality.
There are lists of playlists that are created by the users themselves. If the user is logged in and is on the same page where the player is located with the song, you need to display a list of his own playlists and show that this song is already in his playlists.
List users playlists
Array
(
[0] => stdClass Object
(
[playlist_id] => 1
[title] => My firts playlist
[user] => 20
[date] => 2019-02-15 00:00:00
)
[1] => stdClass Object
(
[playlist_id] => 2
[title] => My another playlist
[user] => 20
[date] => 2019-02-15 00:00:00
)
[2] => stdClass Object
(
[playlist_id] => 3
[title] => My tested playlist
[user] => 20
[date] => 2019-02-15 00:00:00
)
)
Array with all users song added of any playlists
Array
(
[0] => stdClass Object
(
[id] => 5
[playlist_id] => 2
[song] => QhvUVlCt
[user] => 20
[date] => 2019-02-15 20:41:47
)
[1] => stdClass Object
(
[id] => 6
[playlist_id] => 1
[song] => QhvUVlCt
[user] => 20
[date] => 2019-02-16 13:17:11
)
)
As can be seen from the second code, the song with the identifier 'QhvUVlCt' is in two playlists out of three users with the identifier '20'
It’s not difficult to display just playlists to the page, I use the foreach cycle
The difficulty is how to compare keys from two different arrays. For example, as in my example, two playlists (playlist_id = 1 and playlist_id = 2), in which this song already exists, output the mark "Already added to this playlist", and the rest (in my example, this playlist_id = 3) display the mark "Add to this playlist"
Output only playlist:
<?php foreach($playlists as $playlist): ?>
<a href="#" class="playlists__link" data-action="playlist" data-id="<?php echo $playlist->playlist_id; ?>">
<strong span class="playlists__title">
<span class="playlists__icon"><i class="fa fa-bars"></i></span>
<?php echo $playlist->title; ?>
</strong>
</a>
<?php endforeach; ?>
And how to implement a comparison - I can not figure it out
I would really appreciate any help.
I think you should extract playlist ids from second array ($songs) with array_column for example:
$playlistIds = array_column($second_array, 'playlist_id');
Them iterate over $playlists:
foreach($playlists as $playlist):
if (in_array($playlist->id, $playlistIds)) {
// do one thing
} else {
// do another thing
}
endforeach;
Update for array_column: as array_column can extract columns (not really columns, but properties) from objects since php7, you can use simple foreach:
$playlistIds = [];
foreach ($second_array as $song) {
$playlistIds[] = $song->playlist_id;
}
And even a faster version will be:
$playlistIds = [];
foreach ($second_array as $song) {
// here you set `playlist_id` as key
$playlistIds[$song->playlist_id] = true;
}
foreach($playlists as $playlist):
// `isset` is faster than `in_array`
if (isset($playlistIds[$playlist->id])) {
// do one thing
} else {
// do another thing
}
endforeach;

PHP PDO comparison of array element by in_array() method is not working

I need to compare element from an array to another array with in_array() method:
$oldAttachedObjs = array();//this array need to be compare with single element of other loop
$sqlObjAttached = "SELECT sno,ins_sno,obj_sno FROM cases_objections WHERE ins_sno = :ins_sno";
$paramObj = array(':ins_sno'=>$ins_sno);
if($db->dbQuery($sqlObjAttached,$paramObj)){
foreach($db->getRecordSet($sqlObjAttached,$paramObj) as $o){
$oldAttachedObjs[] = $o;
}//foreach()
}
Now i want to compare the above array elements with each element in the iterated loop over the following loop
<?php
$sqlChildren = "SELECT sno,obj_sno,child_lbl FROM list_objection_children WHERE is_active = 1 AND obj_sno = :obj_sno ORDER BY sno ASC";
$param = array(':obj_sno'=>$obj['sno']);
if($db->dbQuery($sqlChildren,$param)){
foreach($db->getRecordSet($sqlChildren,$param) as $ch){
?>
<ul class="obj_ul">
<li>
<div class="checkbox checkbox-primary">
<?php print_r($oldAttachedObjs[0]); ?>
<input type="checkbox" <?php if(in_array($ch['sno'],$oldAttachedObjs['obj_sno'])){ ?> checked <?php //} ?> value="1" id="chk_<?php echo($ch['sno']);?>" name="chk_<?php echo($ch['sno']);?>" class="styled">
<label style="font-weight: normal !important;" for="chk_<?php echo($ch['sno']);?>"><?php echo($ch['child_lbl']); ?></label>
</div>
</li>
</ul>
<?php
}//foreach()
}
?>
in fact it populate the following array:
Array (
[0] => Array ( [sno] => 1 [0] => 1 [ins_sno] => 2 [1] => 2 [obj_sno] => 3 [2] => 3 ),
[1] => Array ( [sno] => 2 [0] => 2 [ins_sno] => 2 [1] => 2 [obj_sno] => 49 [2] => 49 ),
[2] => Array ( [sno] => 3 [0] => 3 [ins_sno] => 2 [1] => 2 [obj_sno] => 52 [2] => 52 ),
[3] => Array ( [sno] => 5 [0] => 5 [ins_sno] => 2 [1] => 2 [obj_sno] => 54 [2] => 54 )
)
but i have no luck to compare, because the array contained with another array and i don't know what to do with this now ?
You need to loop through the parent array to compare to the inner arrays.
foreach($oldAttachedObjs as $objs){
if(in_array('what you are looking for', $objs){
//it is in the array, do what you want
}else{
//it is not in the array, deal with it accordingly
}
}
This way you'll be able to check wether whatever you're looking for is inside one of the results you got from the database

Parse JSON with PHP - irregular format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
New to php and trying to figure out how to parse API data which is returned in what looks like a weird format. Here is a sample of the data:
[{"campaign_id":"9000","date":"2016-01-11","totalcount":"1838","page":"1","totalpages":1,"index":1,"count":1838},{"video2.stack.com":["84254","105","0","83.71"],...,"zierfischforum.at":["1","0","0","0.00"]}]
Here is an example of how you can parse your JSON as an array:
$json_string = '[{"campaign_id":"9000","date":"2016-01-11","totalcount":"1838","page":"1","totalpages":1,"index":1,"count":1838},{"video2.stack.com":["84254","105","0","83.71"],"zierfischforum.at":["1","0","0","0.00"]}]';
$json_array = json_decode($json_string, true); // true gets us an array
echo '<pre>';
print_r($json_array);
echo $json_array[1]['video2.stack.com'][0];
Provides the following results:
Array
(
[0] => Array
(
[campaign_id] => 9000
[date] => 2016-01-11
[totalcount] => 1838
[page] => 1
[totalpages] => 1
[index] => 1
[count] => 1838
)
[1] => Array
(
[video2.stack.com] => Array
(
[0] => 84254
[1] => 105
[2] => 0
[3] => 83.71
)
[zierfischforum.at] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0.00
)
)
)
84254
First we output the entire array. Based on data there we are able to single out a value for one of the array parts for video2.stack.com. It is relatively easy to traverse and you should be able extract any information you need. You could even build a recursive search function for your JSON.
NOTE: I removed some of your data(the part ,...) as it made your JSON non-valid.

echo a multidimensional array into multiple html table rows

I have a query that I'm running and it will output an unknown number of results. I want to display these results in a table of 5 columns. So I need the array print until the sixth result and then start a new row.
The way I tried to do it was to take the original array and chunk it into blocks of 5.
$display=array_chunk($row_Classrooms,5);
which gives me an array like this.
Array (
[0] => Array (
[0] => Array (
[id_room] => 1
[Name] => Classroom 1
[class] => Yes
)
[1] => Array (
[id_room] => 5
[Name] => Classroom 2
[class] => Yes
)
[2] => Array (
[id_room] => 6
[Name] => Classroom 3
[class] => Yes
)
[3] => Array (
[id_room] => 7
[Name] => Classroom 4
[class] => Yes
)
[4] => Array (
[id_room] => 8
[Name] => Classroom 5
[class] => Yes
)
)
[1] => Array (
[0] => Array (
[id_room] => 9
[Name] => Classroom 6
[class] => Yes
)
)
)
I'm then trying to echo this out with a pair of while loops, like such.
while ($rows = $display) {
echo '<tr>';
while ($class = $rows) {
echo'<td>'.$class['name'].'<br>
<input name="check'.$i.' type="checkbox" value="'.$class['id_room'].'></td>';
$i++;
}
echo '</tr>';
}
When I run this it apparently gets stuck in a never ending loop because nothing gets displayed but the browser just keeps chewing up more and more memory :)
The while statements are wrong. Have a look at here - in your while-statement you are always assigning the complete $display - not one entry.
You could try using while(($rows = array_shift($display)) !== false) - that will always get the first array item until there are no more items.
The same case in the second while-statement.
I ended up replacing the while loops with foreach loops instead which solved the issue.
foreach ($display as $rows) {
echo '<tr class="popup">';
foreach($rows as $class) {
if(isset($row_Rego)){
$exist=NULL;
$exist=array_search($class['id_room'], array_column($row_Rego, 'id_room'));
}

Foreach inside for loop complication

I'm having trouble with a loop inside another one. I don't know how to handle this situation and I don't get the expected result - I get my expected result but multiplied.
This is my code:
<div id="view">
<?php
for ($i = 0; $i < sizeof($user_roll_array); $i++):
$roll_data =& $user_roll_array[$i];
$roll_date = $roll_data['time'];
$roll_ids = $roll_data['image_ids'];
$roll_ids = explode('|', $roll_ids);
$roll_key = $roll_data['key'];
foreach ($roll_ids as $image_id):
$image_name = $image->get_name($image_id);
?>
<div class="roll-spot">
<?php echo $image_name; ?>
</div>
<?php endforeach; endfor; ?>
</div>
This is what $user_roll_array contains:
Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[image_ids] => 10|9
[time] => 1359244752
[key] => 8O0F5k8G9Y1H4b7
)
[1] => Array
(
[id] => 2
[user_id] => 1
[image_ids] => 13|12|11|10|9
[time] => 1359245133
[key] => n9G7v49E2Q5h0j7
)
[2] => Array
(
[id] => 3
[user_id] => 1
[image_ids] => 13|12
[time] => 1359285360
[key] => 2Q0t1Z3S2r7n5f9
)
[3] => Array
(
[id] => 4
[user_id] => 1
[image_ids] => 10|9
[time] => 1359285377
[key] => 4L6w6R2r2Q0c1g9
)
[4] => Array
(
[id] => 7
[user_id] => 1
[image_ids] => 10|9
[time] => 1359288800
[key] => 4t1X9P8l9H7C1F6
)
)
Based on the array I create inside the for loop, I need to go through each element and get its name via a method ($image->get_name($id)). Then I need to use these names below.
I expect 5 rows to be returned, but I get 13 rows, and the names are duplicated a few times.
If someone could explain how to fix this, I'd understand the issue and prevent future similar problems to occur.
Thanks a lot.
The reason you are getting 13 results is because although there are 5 top-level iterations, there are 13 sub-iterations (the IDs) which you are looping through.
If you want just the 5 iterations to happen, you shouldn't be doing the sub-loop within them. This is the part of your code which is confusing you:
<? foreach ($roll_ids as $image_id): ?>
<? $image_name = $image->get_name($image_id); ?>
<div class="roll-spot">
<?php echo $image_name; ?>
</div>
<?php endforeach;?>
This foreach is itself inside the main loop, and echoing out a div for each ID has access to. In the life cycle of the main array, this will happen 13 times. The reason you are seeing duplicates is because you have top-level array elements which contain the same IDs as other elements.
remove the ampersand in
$roll_data =& $user_roll_array[$i];

Categories