PHP - sort multidimensional grouped arrays - php

I'm trying to sort following array:
$myArray = array(
"ID" => array(
0,
5,
8,
12,
15
),
"date" => array(
1484391600,
1483910300,
1484920000,
1482393630,
1484391600
),
"name" => array(
"Pete",
"Max",
"Tom",
"June",
"Arend"
),
);
I want to be able to choose which subarray is sorted and in which way (numeric / string) and order (DESC / ASC). All the other subarrays should be sorted accordingly.
Here is some code that worked at first, but when the subarray to sort contained an empty string, it failed: All subarrays where sorted differently.
$sortCatArray = $myArray['name'];
foreach($myArray as $category => $value){
$keepOrigin = $sortCatArray;
array_multisort($keepOrigin, SORT_DESC, SORT_STRING, $myArray[$category]);
}
var_dump($myArray);
Can someone point out what I'm doing wrong.
Also I don't want to rearrange the arrays to match the other sorting solutions as I need the values in the given format.

Related

PHP Definition MultiDimensional Associative Arrays

I have 2 arrays with some sample data and I just want to confirm if I have the terminology correct:
Multidimensional Array:
$names = array([
"name" => "Bob",
"age" => 25,
"level" => 6],
["name" => "Joe",
"age" => 34,
"level" => 6]
);
Multidimensional Associative Array:
$names = array(
"Bob" => array(
"age" => 25,
"diploma" => "DAC",
"level" => 6),
"Joe" => array(
"age" => 34,
"diploma" => "DAC",
"level" => 6)
);
The second is Associative because of the index being the name rather than an index number and MultiDimensional because it has more than one entry.
I know it is not really a programming question requiring a code solution, I am just learning the terminology.
I add my two cents. All said by others is pretty correct, but:
The main difference from associative arrays and "simple" arrays. With "simple" arrays you can do something like this
for( $i = 0; $i < count( $array ) - 1; $i++ ) {
$element = $array[ $i ];
// Do something with $element
}
With associative arrays, you cannot do it and, if you want to traverse all the arrays you have to do something like this
foreach( $array as $key => $element ) {
// Do something with $element
}
This approach (the foreach) can be applied to the "simple" array too, while the first can be applied ONLY to "simple" array
Multidimensional array are simply arrays with AT LEAST one element that is an array, no matter the "type"
By the way, it's always think about arrays as associative arrays, always. It prevents you some very simple mistakes later on
Both arrays are multidimensional associative array.
But in second array you can get details of Bob or Joe by just using their name as key. For example to get details of Bob you can just call:
$names['Bob']
In first array you have to know the id or index of array to which Bob details were stored.

declaring 3d array in php

I need to declare (not define) three dimensional array in PHP and then assign values to it.
For example,
<?php
$item = array(
array("item1", 22, 18),
array("Item2", 15, 13),
array("Item3", 5, 2),
);
?>
This is how I want my array. I first want to declare this $item array and then assign those three values (e.g item1, 22, 18) to it. Please help me with this and also how to access this array.
You said you wanted a three-dimensional array. The current array you have is two-dimensional.
What you might have meant was to have "item#" as a key to your array.
<?php
$item = array(
"item1" => array( 22, 18 ),
"Item2" => array( 15, 13 ),
"Item3" => array( 5, 2 ),
);
?>
You would access an element with $item['item1'], which would give you the array (22,18)

Best way to refer index which contains in array

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

Can I store an array within a multidimensional array? (PHP)

It is possible to put an array into a multi dim array? I have a list of user settings that I want to return in a JSON array and also have another array stored in that JSON array...what is the best way to do that if it isn't possible?
A multi dimension is already an array inside an array. So there's nothing stopping you from putting another array in there. Sort of like dreams within dreams :P
Just use associative arrays if you want to give your array meaning
array(
'SETTINGS' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
),
'DATA' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
)
)
EDIT
To answer your comment, $output_files[$file_id]['shared_with'] = $shared_info; translates to (your comment had an extra ] which I removed)
$shared_info = array(1, 2, 3);
$file_id = 3;
$output_files = array(
'3' => array(
'shared_with' => array() //this is where $shared_info will get assigned
)
);
//you don't actually have to declare it an empty array. I just did it to demonstrate.
$output_files[$file_id]['shared_with'] = $shared_info; // now that empty array is replaced.
any array key can have an array value in php, as well as in json.
php:
'key' => array(...)
json:
"key" : [...]
note: php doesn't support multidimensional arrays as in C or C++. it's just an array element containing another array.

php multidimensional array

I want to create a twodimensional array in php. What is the correct syntax of creating an empty multidimensional array in php.
Secondly I want to create 7 two dimensional array in for
Take a look at the PHP online manual. The first example shows you how to create a multi dimensional array.
http://php.net/manual/en/function.array.php
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
To do what you want in a for loop, you can do so like this
// the following creates a 2d array. the first dimension contains 7 arrays of numbers 1 to 10
$firstDimension = array();
for ($i = 0; $i < 7; $i++) {
$firstDimension[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
Unlike some other langauges (such as standard C), arrays in PHP are "sparse" (i.e.: they only take up the space they need) so you can define a multi-dimensional array simply via:
$testArray = array();
(i.e.: You don't need to reserve the amount of space you're going to require.) However, more usefully, you can add values as follow:
$testArray = array();
$testArray[0][0] = "Hello";
$testArray[0][1] = "World";
...
That said, I'd recommend reading the PHP array manual page, as you might want to use named indexes, etc. and it has better examples.
Multi-dimentional arrays are like regular arrays but the value to some (or all) or their keys are arrays.
For example you can create a two dimentional array like this:
$arr = array();
$arr[1] = array(1 => 'one', 2 => 'two');
And you can use it like this:
echo $arr[1][1]; //which prints "one"
To create empty multidimensional array in PHP, you can do the following.
$arr_1 = array();
Yes. That's all. You can insert any type of data or array in it. There is no specific declaration of various arrays in PHP.
Now, suppose I want to insert data inside this multidimensional array $arr_1. I need to create an array of addresses. Each address item will have city, state and country.
You can do this as follows:
$arr_1[0] = array(
'city' => 'Gurgaon',
'state' => 'Haryana',
'country' => 'India'
);
$arr_1[1] = array(
'city' => 'Los Angeles',
'state' => 'California',
'country' => 'United States'
);
$arr_1[1] = array(
'city' => 'Melbourne',
'state' => 'Victoria',
'country' => 'Australia'
);
You can create as many arrays as you want in this way.
If you want to learn more about PHP arrays (Indexed, Associative, Multidimensional), visit PHP arrays explained with examples - Webolute Blog
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>

Categories