2

I have this array called $items. My CMS created this array with three products and I just did a var_dump with the results below.

array(3) { [0]=> array(11) { ["item_id"]=> string(4) "1320" ["name"]=> string(5) "ITEM_A" ["price"]=> string(6) "$5.00" } 
           [1]=> array(11) { ["item_id"]=> string(4) "1321" ["name"]=> string(5) "ITEM_B" ["price"]=> string(6) "$5.00" } 
           [2]=> array(11) { ["item_id"]=> string(4) "1323" ["name"]=> string(5) "ITEM_D" ["price"]=> string(6) "$5.00" } 
         }

Is there a way I can inject another item, "ITEM_C" into this array so that it's now

array(3) { [0]=> array(11) { ["item_id"]=> string(4) "1320" ["name"]=> string(5) "ITEM_A" ["price"]=> string(6) "$5.00" } 
           [1]=> array(11) { ["item_id"]=> string(4) "1321" ["name"]=> string(5) "ITEM_B" ["price"]=> string(6) "$5.00" } 
           [2]=> array(11) { ["item_id"]=> string(4) "1323" ["name"]=> string(5) "ITEM_D" ["price"]=> string(6) "$5.00" } 
           [3]=> array(11) { ["item_id"]=> string(4) "1322" ["name"]=> string(5) "ITEM_C" ["price"]=> string(6) "$5.00" } 
         }

and then sort it by "name"? I basically want to always add one new row to this array which will always have different names and then sort it by the name. When I do the foreach php command I don't want it to be in the order of ITEM_A, ITEM_B, ITEM_D, ITEM_C. It needs to be ITEM_A, ITEM_B, ITEM_C, ITEM_D.

1 Answer 1

2

Appending to an array in PHP is easy as $array[] :

 $myArray = array(1,2,3);
 $myArray[] = 4; //now array(1,2,3,4)

So to add to your existing array, first create your new array element

$element = array("item_id" => 1322, "name" => "ITEM_C", /*etc.*/);

Then add it your array

$myArray[] = $element;

As for sorting, there are various sort functions depending on your exact needs. Since you're sorting according to a given array key, you'll probably need to call usort with a given function.

function nameCompare($a, $b)
{
    $a = $a["name"];
    $b = $b["name"];
    return strcmp($a, $b);
}

usort($myArray, 'nameCompare');
Sign up to request clarification or add additional context in comments.

2 Comments

$myArray[] = 4; works good but how do I assign it to specific column names like "item_id" and "name"?
Just create that sub-array first. I've updated my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.