Array Combine in PHP - php

I am trying to combine keys and values in arrays. I have an product_id with different price.
Let say
Product id and price
id 101 and price is 100
id 105 and price is 200
id 101 and price is 300
list of product ids in array with $product_ids[] and list of price also $price_amount[]
So I preferred to combine the two arrays using array_combine
I made array_combine($product_ids,$price_amount);
Now it appears look like this way
array(2) { [101]=> float(100) [105]=> float(300) }
Is there is a way to add the key elements to the id as something like
array(2) {
[101] => float(400) (100+300)
[105] => float(300)
}
Here is the idea i tried
$products = array();
$order_totalss = array();
foreach (get_posts('post_type=shop_order&numberposts=-1&post_status=publish') as $order) {
$order = new WC_Order($order->ID);
if (wc_customer_bought_product($order->billing_email, $order->user_id, $product_id)) {
$productcounts[] = $product_id;
$order_totalss[] = $order->get_total();
}
}
$arraymergeme = array_combine($productcounts, $order_totalss);

You will have to do this manually I'm afraid:
$total = array();
foreach ($product_ids as $key => $value) {
// each value of product_ids becomes the key
if (isset($total[$value])) {
// we have seen this key before
$total[$value] += $price_amount[$key];
} else {
// new key
$total[$value] = $price_amount[$key];
}
}

Simple code so you can see what's happening clearly:
$ids = array(101, 105, 101);
$prices = array(100, 200, 300);
$totals = array();
foreach ($ids as $key => $id)
{
// Make sure index is defined
if ( ! isset($totals[$id]))
{
// Make sure we have a value
$totals[$id] = 0;
}
// Assuming index $key matches... add to the total
$totals[$id] += $prices[$key];
}

PHP arrays are associative so you can write something like: price['101'] = 100 thereby using the product id as the array index.

Thinking you are looking for something like this. I haven't done php in awhile, so the syntax may need tweaking, but I think the logic is correct.
$cart = array(
"101" => 100,
"105" => 200,
"101" => 300
);
$product_id_arr = array();
foreach ($cart as $product_id => $price) {
if(array_key_exists($product_id, $product_id_arr)){
$product_id_arr[$product_id] = $product_id_arr[$product_id] + $price;
}else{
$product_id_arr[$product_id] = $price;
}
}

array_combine will not do the trick for you. You will have to iterate through the array and total them as you go. Here's an example:
<?php
$product_ids = array('101', '105', '101');
$price_amount = array(100, 200, 300);
$combined = array();
$productCount = count($product_ids);
for($i = 0; $i < $productCount; $i++) {
// if this product_id is not in the $combined array, add its price
// as associative array ('101'=>100)
// but if it is found in $combined, add to its current price
if (!array_key_exists($product_ids[$i], $combined)) {
$combined[$product_ids[$i]] = $price_amount[$i];
} else {
$combined[$product_ids[$i]] += $price_amount[$i];
}
}
print_r($combined);
?>
Results:
Array
(
[101] => 400
[105] => 200
)

Try this
$final_arr = array();
for($i=0;$i<count($product_ids);$i++) {
if(!isset($final_arr[$product_ids[$i]])) {
$final_arr[$product_ids[$i]] = 0;
}
$final_arr[$product_ids[$i]] += $price_amount[$i];
}

Yes you can add key elements to id, basically an array can be created by using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
the one you are looking for is associative array. you can definitely specify the key you want and store the value you want at that key.
here is a link that would be helpful

Related

In PHP how do I remove duplicates in an array of objects where a duplicate is defined as a subset of key-value pairs having the same value

I have an array of the form:
class anim {
public $qs;
public $dp;
public $cg;
public $timestamp;
}
$animArray = array();
$myAnim = new anim();
$myAnim->qs = "fred";
$myAnim->dp = "shorts";
$myAnim->cg = "dino";
$myAnim->timestamp = 1590157029399;
$animArray[] = $myAnim;
$myAnim = new anim();
$myAnim->qs = "barney";
$myAnim->dp = "tshirt";
$myAnim->cg = "bird";
$myAnim->timestamp = 1590133656330;
$animArray[] = $myAnim;
$myAnim = new anim();
$myAnim->qs = "fred";
$myAnim->dp = "tshirt";
$myAnim->cg = "bird";
$myAnim->timestamp = 1590117032286;
$animArray[] = $myAnim;
How do I create a new array containing only the non-duplicates (and the latest entry where duplicates are found) of $animArray, where a duplicate is defined as:
one where $myAnim->dp has the same value as that of another array element's $myAnim->dp AND the $myAnim->cg from the first and the $myAnim->cg from the second have the same value as each other.
In the example above, only the first element is unique by that definition.
I'm hoping there's an elegant solution. I've been through all the array functions in the PHP manual but can't see how it could be achieved.
I could loop through each array element checking if $myAnim->dp has the same value as that of another array element's $myAnim->dp, saving the matches into a new array and then looping through that new array, checking for its $myAnim->cg matching the $myAnim->cg of any other element in that new array.
A more elegant solution would allow me to to change which combination of key-value pairs determine whether there's a duplicate, without having to recast much code.
Does such a solution exist?
Thanks for helping this novice :)
While there is nothing built-in that can be used directly out of the box, there isn't a lot of code necessary to handle an arbitrary number of properties to consider for uniqueness. By keeping track of each unique property in a lookup array, we can build an array where the leaf nodes (i.e. the ones that isn't arrays themselves) are the objects.
We do this by keeping a reference (&) to the current level in the array, then continue building our lookup array for each property.
function find_uniques($list, $properties) {
$lookup = [];
$unique = [];
$last_idx = count($properties) - 1;
// Build our lookup array - the leaf nodes will be the items themselves,
// located on a level that matches the number of properties to look at
// to consider a duplicate
foreach ($list as $item) {
$current = &$lookup;
foreach ($properties as $idx => $property) {
// last level, keep object for future reference
if ($idx == $last_idx) {
$current[$item->$property] = $item;
break;
} else if (!isset($current[$item->$property])) {
// otherwise, if not already set, create empty array
$current[$item->$property] = [];
}
// next iteration starts on this level as its current level
$current = &$current[$item->$property];
}
}
// awr only calls the callback for leaf nodes - i.e. our items.
array_walk_recursive($lookup, function ($item) use (&$unique) {
$unique[] = $item;
});
return $unique;
}
Called with your data above, and the requirement being that uniques and the last element of duplicates being returned, we get the following result:
var_dump(find_uniques($animArray, ['dp', 'cg']));
array(2) {
[0] =>
class anim#1 (4) {
public $qs =>
string(4) "fred"
public $dp =>
string(6) "shorts"
public $cg =>
string(4) "dino"
public $timestamp =>
int(1590157029399)
}
[1] =>
class anim#3 (4) {
public $qs =>
string(4) "fred"
public $dp =>
string(6) "tshirt"
public $cg =>
string(4) "bird"
public $timestamp =>
int(1590117032286)
}
}
Which maps to element [0] and element [2] in your example. If you instead want to keep the first object for duplicates, add an isset that terminates the inner loop if property value has been seen already:
foreach ($properties as $idx => $property) {
if ($idx == $last_idx) {
if (isset($current[$item->$property])) {
break;
}
$current[$item->$property] = $item;
} else {
$current[$item->$property] = [];
}
// next iteration starts on this level as its current level
$current = &$current[$item->$property];
}
It's important to note that this has been written with the assumption that the array you want to check for uniqueness doesn't contain arrays themselves (since we're looking up properties with -> and since we're using array_walk_recursive to find anything that isn't an array).
This was fun:
array_multisort(array_column($animArray, 'timestamp'), SORT_DESC, $animArray);
$result = array_intersect_key($animArray,
array_unique(array_map(function($v) { return $v->dp.'-'.$v->cg; }, $animArray)));
First, extract the timestamp and sort that array descending, thereby sorting the original array.
Then, map to create a new array using the dp and cg combinations.
Next, make the combination array unique which will keep the first duplicate encountered (that's why we sorted descending).
Finally, get the intersection of keys of the original array and the unique one.
In a function with dynamic properties:
function array_unique_custom($array, $props) {
array_multisort(array_column($array, 'timestamp'), SORT_DESC, $array);
$result = array_intersect_key($array,
array_unique(array_map(function($v) use ($props) {
return implode('-', array_map(function($p) use($v) { return $v->$p; }, $props));;
},
$array)));
return $result;
}
$result = array_unique_custom($animArray, ['dp', 'cg']);
Another option would be to sort it ascending and then build an array with a dp and cg combination as the key, which will keep the last duplicate:
array_multisort(array_column($animArray, 'timestamp'), SORT_ASC, $animArray);
foreach($animArray as $v) {
$result[$v->dp.'-'.$v->cg] = $v;
}
In a function with dynamic properties:
function array_unique_custom($array, $props) {
array_multisort(array_column($array, 'timestamp'), SORT_ASC, $array);
foreach($array as $v) {
$key = implode(array_map(function($p) use($v) { return $v->$p; }, $props));
$result[$key] = $v;
}
return $result;
}
$result = array_unique_custom($animArray, ['dp', 'cg']);
//Create an array with dp and cg values only
$new_arr = [];
foreach($animArray as $key=>$item) {
$new_arr[] = $item->dp.','.$item->cg;
}
$cvs = array_count_values($new_arr);
$final_array = [];
foreach($cvs as $cvs_key=>$occurences) {
if ($occurences == 1) {
$filter_key = array_keys($new_arr, $cvs_key)[0];
$final_array[$filter_key] = $animArray[$filter_key];
}
}
The final result would be (from your example) in $final_array:
[0] => anim Object
(
[qs] => fred
[dp] => shorts
[cg] => dino
[timestamp] => 1590157029399
)
Some explanation:
//Create a new array based on your array of objects with the attributes dp and cg
//with a comma between them
$new_arr = [];
foreach($animArray as $key=>$item) {
$new_arr[] = $item->dp.','.$item->cg;
}
/*
$new_arr now contains:
[0] => shorts,dino
[1] => tshirt,bird
[2] => tshirt,bird
*/
//Use builtin-function array_count_values to get the nr of occurences for
//each item in an array
$cvs = array_count_values($new_arr);
/*
$cvs would contain:
(
[shorts,dino] => 1
[tshirt,bird] => 2
)
*/
//Iterate through the $cvs array.
//Where there are only one occurence (no duplicates)
//create a final array $final_array
$final_array = [];
foreach($cvs as $cvs_key=>$occurences) {
if ($occurences == 1) {
/*
array_keys with second argument $csv_key searches for key with
with the key from $cvs-key
so basically search for:
shorts,dino and retrieve the key 0 (first element)
*/
$filter_key = array_keys($new_arr, $cvs_key)[0];
/*
Add a new item to the $final_array based on the key in
the original array $animArray
if you don't want the original key in the new array
you could just do $final_array[] instead of
$final_array[$filter_key]
*/
$final_array[$filter_key] = $animArray[$filter_key];
}
}
You said you would like to have some kind of functionality test different attributes. I believe it would just be making a function/method where you pass in two values to the arguments $attr1 ('dp'?), $attr2('cg'?) or similar.
UPDATE
I had not grasped that you wanted the last value as well. This actually seemed as an easier task. Maybe I am missing something but it was fun to come up with a different approach than other answers :-)
//Create an array with dp and cg values only
$new_arr = [];
foreach($animArray as $key=>$item) {
$new_arr[] = $item->dp.','.$item->cg;
}
//Sort keys descending order
krsort($new_arr);
//Because of sending order of keys above, the unique values would return the
//last item of the duplicates
$new_arr2 = array_unique($new_arr);
//Switch order of keys back to normal (ascending)
ksort($new_arr2);
//Create a new array based on the keys set in $new_arr2
//
$final_arr = [];
foreach($new_arr2 as $key=>$item) {
$final_arr[] = $animArray[$key];
}
The output of $final_arr[] would be (in your example)
Array
(
[0] => anim Object
(
[qs] => fred
[dp] => shorts
[cg] => dino
[timestamp] => 1590157029399
)
[1] => anim Object
(
[qs] => fred
[dp] => tshirt
[cg] => bird
[timestamp] => 1590117032286
)
)

create a grouped array from another array

I have a big array (read from a file)
$data = array(
array(134, 'Field_A_134', 'Field_B_134'),
array(134, 'Field_C_134', 'Field_D_134'),
array(134, 'Field_E_134', 'Field_F_134'),
array(180, 'Field_A_180', 'Field_B_180'),
array(70, 'Field_A_70', 'Field_B_70'),
array(180, 'Field_C_180', 'Field_D_180'),
...
);
and i want to group into another array by the first key from the first array (ex: 134, 180, 70, ...). Those keys are repeating, but the fields are different.
The array i want to make is:
array(
'134' => array(array(134, 'Field_A_134', 'Field_B_134'), array(134, 'Field_C_134', 'Field_D_134'), array(134, 'Field_E_134', 'Field_F_134')),
'180' => array(array(180, 'Field_A_180', 'Field_B_180'), array(180, 'Field_C_180', 'Field_D_180')),
'70' => array(array(70, 'Field_A_180', 'Field_B_180'))
);
Each key contains an array of arrays that contain the first key.
I was trying to make this:
$f = array();
$pr = array();
foreach($data as $p){
if(isset($f[$p[0]])){
array_push($f[$p[0]], $p);
} else {
$f[$p[0]] = $p;
}
array_push($pr, $f);
}
but it`s not what i want.
The error is in the else part. You need to assign an array, like this:
$f[$p[0]] = [$p];
Or like this, since PHP will create the array on the fly:
$f[$p[0]][] = $p;
And since that code can also be used when the array already exists, you can simplify to this loop:
foreach($data as $p) {
$f[$p[0]][] = $p;
}

PHP populate multi-dimensional array with data from many foreach

I am scraping an ecommerce website and need to get some data from products, like product name, price, ...
For that, I have:
...
// library includes...
$html = file_get_html($link);
foreach($html->find('.productBoxClass') as $element){
foreach($element->find('.productTitle') as $product) {
$product = $product->plaintext;
}
foreach($element->find('.price') as $price) {
$price = $price->outertext;
}
// and so on...
}
I wanna save this data in a database. So, I want to save all the data in an array for after verify each product if I have to insert or just update. I am intending to populate an multi-dimensional array with this data:
Each position of the array with another array containing the information about one product... To make it easier to save in the database after...
Any help?
This seems like an abnormal data structure or you should be looping through it differently. But if it is an abnormal structure and the product and price aren't grouped together, they are just listed in the same order, then this should work:
$products = [];
$i = 0;
foreach($element->find('.productTitle') as $product) {
$products[$i++]['product'] = $product->plaintext;
}
$i = 0;
foreach($element->find('.price') as $price) {
$products[$i++]['price'] = $price->outertext;
}
Note the $i++ as the key which will increment $i each loop.
If the product and pricing are grouped together in an element, then you should be looping on that element and there should be no need for a foreach for product and price.
Please check the below code, let me know your thoughts...
<?php
// library includes...
$html = file_get_html($link);
$productArr = array();
foreach($html->find('.productBoxClass') as $element){
$tempArr = array('title' => '','price' => 0,'other' => ''); // declare temp array for stroing each product nodes
foreach($element->find('.productTitle') as $product) {
$tempArr['title'] = $product->plaintext; // To do check for empty text here
}
foreach($element->find('.price') as $price) {
$tempArr['price'] = $price->outertext; // To do validate the price
}
foreach($element->find('.other-features') as $price) {
$tempArr['other'] = $price->outertext; // To do validate the price
}
// and so on... with $tempArr['key']
// then assign
$productArr[] = $tempArr; // save temp array in global product array
}
// Product array
echo '<pre>';print_r($productArr);die;
Use in first foreach the count item:
...
// library includes...
$html = file_get_html($link);
// Array declaration
$products = array();
foreach($html->find('.productBoxClass') as $i => $element){
foreach($element->find('.productTitle') as $product) {
$products[$i]['name'] = $product->plaintext;
}
foreach($element->find('.price') as $price) {
$products[$i]['price'] = $price->outertext;
}
// and so on...
}
And will result:
Array
(
[0] => Array
(
[name] => Product 1
[price] => 1.00
)
[1] => Array
(
[name] => Product 1
[price] => 1.00
),
...
)

Associative Array - duplicated key values

I am doing a simple shopping application were user may choose books from the store based on the title, price, quantity etc. At the moment all details of the books are kept in an associative array which looks like this:
$menu = array(
array ('id' => '1', 'catagory' => 'newbooks','title' => 'Alex','price' => 4.95, 'desc' => 'bbbb'),
array('id' => '2','catagory' => 'newbooks','title' => 'David ','price' => 5.95, 'desc' => 'sss'),);
}
What I am trying to achieve is merge or remove duplicated entries of book id's also each book title will be printed in one single row containing 'title', 'id', 'price'
for example:
Alex qty:2 price 4.95
David qty:2 price 5.95
and so on...
And this is my cart file:
$buy = array();
$qty = 0;
$total = 0;
foreach ($_SESSION['buy'] as $id) {
foreach ($menu as $book ) {
if ($book['id'] == $id) {
$buy[] = $book;
$total += $book['price'];
}
}
}
}
if (count($buy) > 0)
if (count($book) > 0)
{
echo"<table>";
echo"<tr><th>Item Description</th><th>Quantity</th><th>Price</th></tr>";
foreach ($buy as $book){
$f_price = sprintf("%0.2f", $book["price"]);
echo"<tr><td>" .$book["title"] ."</td>";
echo"<td>" .$qty."</td><";
echo"<td>" .$f_price."</td></tr>";
}
echo"<tr><td>Total</td><td>".$total."</td></tr>";
echo"</table>";
}
I will be extremely grateful for any help or advice cause I spent long long time to resolve this problem trying use unique functions, for statements foreach loop but in vain I am still novice also please try to be a little tolerant . Cheers!
Untested but this should do what you want using array_count_values to obtain the quantities you were looking for along with a few changes to make the script more efficient and easier to manage.
<?php
//the ids of the items the user wants to buy
$ids=$_SESSION['buy'];
//Your database of items
$menu = array(
array ('id' => '1', 'catagory' => 'newbooks','title' => 'Alex','price' => 4.95, 'desc' => 'bbbb'),
array('id' => '2','catagory' => 'newbooks','title' => 'David ','price' => 5.95, 'desc' => 'sss')
);
//Create a reverse look-up for the database
$lookUp=array();
foreach($menu as $i=>$v)$lookUp[$v['id']]=$menu[$i];
//populate the cart with items, their quantities, and a total
$cart = array();
$total = 0;
foreach (array_count_values($ids) as $id=>$quantity)
{
if (!array_key_exists($id, $lookUp))continue;
$item=$lookUp[$id];
$itemTotal=$item['price']*$quantity;
$total+=$itemTotal;
$cart[]=array_merge($item,array('quantity'=>$quantity,'itemTotal'=>$itemTotal));
}
if(count($cart) > 0)
{
echo '<table>';
echo '<tr><th>Item Description</th><th>Quantity</th><th>Price</th><th>Item Total</th></tr>';
foreach ($cart as $item)
{
echo sprintf('<tr><td>%s</td><td>%s</td><td>%0.2f</td><td>%0.2f</td></tr>',
$item["title"],$item['quantity'],$item['price'],$item['itemTotal']);
}
echo '<tr><td colspan="3" style="text-align:center;">Total</td><td>'.$total.'</td></tr>';
echo '</table>';
}
If it's just based off the id, when you build the array, store the book id as the key in the larger array, so your end array would be:
$books = array(
1=> array ('id' => '1', [...]),
2=> array ('id' => '2', [...])
);
You could also add some code that checks when you try to assign a value to that array to see if the key is already set.
if(!isset($books[$book_id])){
//Add to the array
}else{
//Maybe display an error?
}
PS: Category only has one a in it.
It's a pretty cumbersome way to make a stock overview of the books in your collection, but that aside :)
If i was to work with an array like that, (and i would never do that :)) i would first select all unique keys, and then go through them one by one, counting the number of times it occur in the $menu array.
As follows:
$unique_books = array_unique($menu);
foreach($unique_books as $book){
$qty = array_keys($menu, $book["id"])
$book["qty"] = $qty;
$stock = $book;
}
As you can see, now $stock will be the unique array, with a qty added to it, containing the number of times, the id was seen in $menu.
This is just a fast code block, and should be testet, but the theory works i think. As i mentioned before, the way you'r making this in the first place, is not very smart, and you should really reconsider the whole thing imo :)
If you don't wanna duplicates simple use the book_id as the key of buy array
Example:
$menu = array(
array('id' => '1', 'catagory' => 'newbooks','title' => 'Alex','price' => 4.95, 'desc' => 'bbbb'),
array('id' => '2','catagory' => 'newbooks','title' => 'David ','price' => 5.95, 'desc' => 'sss')
);
$session=array(1,2,2,2,1);
$buy = array();
foreach ($session as $id) {
foreach ($menu as $book) {
if ($book['id'] == $id) {
if(isset($buy[$id])){
$buy[$id]['qty']++; // increase quantity
$buy[$id]['total'] += $book['price']; // total price only for this id
$buy['total'] += $book['price']; // All ids price total
}else{
$buy[$id] = $book; // assign new id to the buy array
$buy[$id]['qty'] = 1; // quantity reset to 1
$buy[$id]['total'] = $book['price']; // id price
$buy['total'] += $book['price']; // total price
}
}
}
}
print_r($buy);
You can test it here!
http://codepad.org/wH2WskLG
Instead of merging duplicates you should add book id and qty as array row to session.
On session start..
if (!isset($_SESSION['buy']))
$_SESSION['buy'] = array();
When adding new..
$new_book = $added_book; // just for example
$qty = $added_qty; // Added qty
// Check if book already exists in shopping cart and update qty
if (array_key_exists($new_book['id'], $_SESSION['buy'])) {
$_SESSION['buy'][$new_book['id']] += $qty;
} else {
$_SESSION['buy'][$new_book['id']] = $qty;
}
Then on shopping cart view just loop thru your items..
foreach($menu as $book ) {
if (array_key_exists($book['id'], $_SESSION['buy'])) {
// User bought this book..
$qty = $_SESSION['buy'][$book['id']];
}
}

find id of post with highest value

I have an array of posts that I want to sort - but before I do, I want to find the id of the post with the highest number of likes.
I loop through the array using a foreach. Although it seems like a waste to do two foreach loops for this - I don't know if there's an alternative when trying to find the highest value beforehand?
Array
(
[0] => Array
(
[id] => 162
[like_count] => 2
etc.
)
[1] => Array
(
[id] => 165
[like_count] => 23
etc.
)
)
So the second post has the highest amount of likes, so I need the ID of 165 - then when I loop through I can do something like
foreach ($posts as $post){
if($most_liked_id == $post["id"]){
// this post is the most liked!
}
}
Any help would be much appreciated - thanks!
$highest = 0;
$highest_id = 0;
foreach($array as $a) {
if($a['like_count'] > $highest) {
$highest = $a['like_count'];
$highest_id = $a['id'];
}
}
Hope I understood you correctly :)
This looks like data retrieved from a database. If so, use the ORDER BY like_count DESC clause in the SQL.
The ID of the post with the most likes will then be at $posts[0]['id'] before you sort by your other method.
very easy task, you loop through your posts.
function get_max_like_post($posts) {
$max_like = 0;
$max_like_post = array();
foreach ($posts as $post) {
if ($post['like_count'] > $max_like) {
$max_like = $post['like_count'];
$max_like_post = $post;
}
}
return $max_like_post['id']
}
You could use usort.
$posts = array(
array('id' => 161, 'like_count' => 0),
array('id' => 162, 'like_count' => 6),
array('id' => 4, 'like_count' => 2),
);
function like_sort($a, $b) {
if ($a['like_count'] == $b['like_count']) {
return 0;
}
return ($a['like_count'] > $b['like_count']) ? -1 : 1;
}
usort($posts, 'like_sort');
// The first element in the array is now the one with the highest like_count.
echo $posts[0]['id']; // 162
Try this:
usort($posts, function($item) { return -$item['like_count']; });
$id = empty($posts) ? null : $posts[0]['id'];
Where $posts is the input array.
Explanation:
first you sort the posts by like count in decreasing fashion
then you get the top post id if there any posts, null otherwise.
What's good about this solution is that you can also select first n posts.
$highest_post_likes = 0;
$highest_post_id = 0;
for($i = 0; $i < sizeof($posts); $i++) {
if ( $posts[$i][like_count] > $highest_post_likes ) {
$highest_post_likes = $posts[$i][like_count];
$highest_post_id = $i;
}
}
// now you can use $posts[$highest_post_id]
Is those datas came from a database like MySQL? If is it, the simpliest solution is to put an "ORDER BY".
You can also make seperate the 'like_count' array keeping the same key than your first array and doing a asort (http://www.php.net/manual/fr/function.asort.php). You will have the key of the highest like count.
You can sort the array in descending order based on like_count and then pick up the id for the first array element.
You can use max function to get the highest value of likes:
foreach ($posts as $post){
$max[]=$post['like_count'];
}
echo max($max['id']);

Categories