Im wondering if array_column keeps the array elements order so when i call the function twice in same array, i can trust the resulting arrays will match. I need to work this way because in the code I have to make many operations with only specific data (one of the keys, in the example, the id), and after all, use both of them (in example id and qty) to insert in db.
Example:
QUERY: SELECT id, qty FROM items ...
CONVERTED INTO ASSOCIATIVE ARRAY:
$array = [
['id' => 1, 'qty' = 2],
['id' => 2, 'qty' = 4]
];
$itemsIds = array_column($array, 'id');
$itemsQty = array_column($array, 'qty');
Can i do?:
for($i = 0; $i < count($array); $i++) {
echo $itemsIds[$i] . $itemsQty[$i];
}
And i will always get the correct data for each item?
Since the DB result is row-based (usually), every column will have some value (even if it's NULL
). So unless you mess with the result somehow, you should be safe. I do practically the same in some of my code.
What if you get all values which you need through SQL query and print it with something like:
$arrayLength = count($array); // Better optimization than do it in every loop
for($i = 0; $i < $arrayLength; $i++) {
echo $array[$i]['id'] . $array[$i]['qty'];
}
That will make you sure that all match with all, and that they have the same quantity of rows.
From your code it seems like you wanna keep keys corresponding to it's value correctly after you use array_column
twice.
But for you information you can get this by using array_column
just once like this:
$items = array_column($array, 'qty', 'id')
Now you get an associative array which keys are each rows id and values are each rows qty.
The third parameter's meaning of array_column
is
The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.
You can find more explains and examples from documentation: http://php.net/manual/en/function.array-column.php