Change position of elements in array - php

I have a simple question:
Query returns array in which I would like to change order of elements in PHP.
I have an array like this:
$typesSumAr = array( 'break', 'private absence', 'sick leave', 'vacation', 'work', 'work absence' );
I would like to have an array in this order:
$typesSumAr = array( 'work', 'break', 'sick leave', 'vacation', 'private absence', 'work absence' );
The are not always all elements in array, it could be only two for example, so I cannot hardcode the array. Do I need to make if statemenets to find out if key exists and then order it manually?
Thank you for your answer.

Seeing as you have an array in the order you prefer, your problem boils down to keeping the elements that are also present in another array. PHP has a function for exactly that: array_intersect
array_intersect returns an array containing all the values of its first array argument that are present in all the arguments. Note that keys are preserved.

There are lots of great array sorting function depending on how you want to sort it. Have a look here http://www.php.net/manual/en/array.sorting.php or even based on your own function via uksort (http://www.php.net/manual/en/function.uksort.php)

Related

Restructure 2d array so that column values become row values (transpose but preserve first level keys)

The situation is as follows. I have a parent array which looks like the following:
$parent = [
1 => ['test1', 'test2'],
2 => ['test1_1', 'test2_2'],
];
I would like to group the data by column.
Desired result:
[
1 => ['test1', 'test1_1'],
2 => ['test2', 'test2_2'],
]
1 parent array called parent contains 2 arrays inside. I want to combine these two so that they have the same values as stated above. So this would mean that the arrays should be combined based on index number.
Since I do not make use of string keys, how would I accomplish this? I believe that there is no build in function available for this situation.
I would imagine that I could start beginning to create a new array and use a for loop through the parent array.
I tried the array-combine function however, this is NOT displaying the results I want.
[
1 => ['test1' => 'test1_1', 'test2' => 'test2_2'
]
If you need to preserve those first level keys, you can re-apply them after tranposing.
Code: (Demo)
var_export(
array_combine(array_keys($parent), array_map(null, ...$parent))
);
Otherwise, you can just transpose and accept the re-indexed first level keys. Honestly, I can't see any good reason to preserve the first level keys because by transposing, you remove the initial association between first level keys and the row values.
Code: (Demo)
var_export(
array_map(null, ...$parent)
);
If these techniques do not suit your actual project data, then we will need a more realistic sample array to be provided in your question body.
Loop over the keys of the top-level array. Then use the current index of the iteration to get the corresponding columns of the nested arrays.
$result = [];
foreach (array_keys($parent) as $i => $k) {
$result[$k] = array_column($parent, $i);
}
DEMO
This assumes the number of rows is the same as the number of columns. It's not clear what you expect the result to be if that's not true.

PHP array as array key

Is it possible in php to make an array an array key as well?
Example:
array(
array('sample', 'abc') => 'sample value'
);
No, if you read the manual
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
And :
The key can either be an integer or a string. The value can be of any type.
This is not possible - array keys must be strings or integers.
What you could do is use serialize:
$myArr = array( serialize(array('sample', 'abc')) => 'sample value');
Which will be the same as:
$myArr = array( 'a:2:{i:0;s:6:"sample";i:1;s:3:"abc";}' => 'sample value');
and could be accessed like:
echo $myArr[serialize(array('sample', 'abc'))];
But note that the serialised string which would be the unique identifier for the array item is clearly fairly complicated and almost impossible to type by hand.
PHP arrays can contain integer and string keys while since PHP does not distinguish between indexed and associative arrays.
Look for php manual Php Manual
whats wrong with
array(
'sample value' => array('sample', 'abc')
);
you could then do
foreach($array as $string => $child){
...
}
and use the $child for whatever purpose

PHP Activerecord array of objects, what next?

Assume the following association among three tables in a database:
//working with three tables a client 'has one' business
//and a business has many business hours.
The following would give us an array of Activerecord objects:
$this->client->business->businesshours
and we would have to pull an object form the array to get its column value:
$this->client->business->businesshours[0]->start_time
Since I am new to PHP Activerecord, what are some ways of proceeding to pull/sort/use information from an array of objects other than looping with a foreach() loop? Are there methods to sort through the array of objects, pull information based on a column value, any best practices?
There is not a library-specific practice for sorting or pulling certain businesshour objects out of the result array. If you want to manipulate the returned array of objects you need to use standard PHP array functions like array_map on the result array.
If you know the sort order or the conditions you want for the returned objects in the result array you should instead specify these in your association declaration so you don't return objects that you don't want or need.
Since you haven't posted any code you'll just have to extrapolate to your own situation from this example:
static $has_many = array(
array(
'businesshours',
'conditions' => array('hour BETWEEN ? AND ?' => array(9, 17)),
'order' => 'hour ASC'
)
);
This association declaration will return only the businesshour objects between 9 and 17 and do it in ascending order. So as you can see, if you constrain your associations to only the records you need, there will be no need to sort or parse the result array once received.
Sometimes it's useful to use array_map to get only certain objects from your result array:
// get $result array
$new = array_map(function($obj) { if ($obj->hour > 9){ return $obj; } }, $result);

JSON get highest to lowest value data multi array

Hello whew im stack in this problem.... arranging value from highest to lowest in json data values
pastebin - http://pastebin.com/yjFUfdJW for the codes
whew i just want to sort the likes highest to lowest... whew anyone has a solution for it? :) pleas help.. :)
Use one of PHP's sort functions for array sorting on the array-value of your JSON?
In order to sort your associative array and maintain the correlation between array elements, you need to use asort().
...
$like[] = array(
'uid' => $uid[$i],
'likes' => $datacount
);
foreach($like as $userlikes)
{
// Sort array numerically
asort($userlikes, SORT_NUMERIC);
}
...

Sorting multidimensional array

I am adding elements to multidimensional array like this
foreach($results as $res){
$fwidth=$res[0];
$fpath=$res[1];
$sub = array (
'img_w' => $fwidth,
'img_path' => $fpath,
);
$widths[] = $sub;
}
And i want to sort $widths array by 'img_w' from bigger to smaller (DESC).
Can anyone help me? Thanks in advance.
Use PHP's USort() function (user sort), which takes two arguments. The first is the array you want to sort. The second is a function that does the actual sorting (you write it yourself). The page I linked to has some examples that should cover your case.

Categories