John Davidson

Tried everything I found on stack but nothing worked to modify my array php

0 comments
Message:


I can't modify an array no matter what I do and I tried everything I found on stack without success. I have no error message and the array just doesn't change.


I have an array containing smaller arrays


$a=array('Champagne 1er Cru Le Cran Domaine Bereche 2010');
$b=array('Champagne 1er Cru Le Cran Domaine Bereche 2011 Magnum');
$c=array('Champagne 1er Cru Extra Brut Bulle de Rose Domaine Savart NV');
$d=array('Champagne 1er Cru Le Cran Domaine Bereche 2010 Magnum');
$e=array('Champagne 1er Cru Monts Fournois Domaine Bereche 2012');
$f=array('Champagne 1er Cru Brut Expression Nature Domaine Savart 2014');
$g=array('Champagne 1er Cru Le Cran Domaine Bereche 2009');

$array=array($a, $b, $c, $d, $e, $f, $g);

Here's the code


foreach($array as $element) {
uasort($array, 'sort_by_name');

function sort_by_name($a, $b)
{
return strcmp($a[0], $b[0]);
}

and the order of the arrays doesn't change at all. And the array is declared in the same function.



My Answer:
The issue here is that you are trying to modify the array while iterating over it, which can cause unexpected results. Instead, you should first sort the array and then iterate over it. Here's the corrected code:

php
function sort_by_name($a, $b)
{
return strcmp($a[0], $b[0]);
}

$array = array($a, $b, $c, $d, $e, $f, $g);
uasort($array, 'sort_by_name');

foreach($array as $element) {
// Your code to work with the sorted array
}


By sorting the array before iterating over it, you ensure that the order is correct and that any modifications you make to the array will be reflected accurately.

Rate this post

4 of 5 based on 8266 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us