I have an array of arrays like so:
array( array(), array(), array(), array() );
the arrays inside the main array contain 4 keys and their values. The keys are the same among all arrays like this:
array( 'id' => 'post_1',
'desc' => 'Description 1',
'type' => 'type1',
'title' => 'Title'
);
array( 'id' => 'post_2',
'desc' => 'Description 2',
'type' => 'type2',
'title' => 'Title'
);
So I want to create another array and extract the id and type values and put them in a new array like this:
array( 'post_1' => 'type1', 'post_2' => 'type2'); // and so on
The keys in this array will be the value of id key old arrays and their value will be the value of the type key.
So is it possible to achieve this? I tried searching php.net Array Functions but I don't know which function to use?
PHP 5.5 introduced an array function that does exactly what you want.
I'm answering this in hopes that it may help someone in future with this question.
The function that does this is array_column.
To get what you wanted you would write:
array_column($oldArray, 'type', 'id');
To use it on lower versions of PHP either use the accepted answer or take a look at how this function was implemented in PHP and use this library: https://github.com/ramsey/array_column
Just use a good ol' loop:
$newArray = array();
foreach ($oldArray as $entry) {
$newArray[$entry['id']] = $entry['type'];
}
Related
I'm writing a php web application where I have a nested array which looks similar to the following:
$results = array(
array(
array(
'ID' => 1,
'Name' => 'Hi'
)
),
array(
array(
'ID' => 2,
'Name' => 'Hello'
)
),
array(
array(
'ID' => 3,
'Name' => 'Hey'
)
)
);
Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.
My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.
Here is the code I have so far:
public function filterArray($results) {
$outputArray = array();
foreach ($results as $key => $row) {
}
return $outputArray;
}
Would anyone be able to suggest the most effective way to achieve what I am after?
Thanks :)
Simply use call_user_func_array as
$array = call_user_func_array('array_merge', $results);
print_r($array);
Demo
I have a multilevel array as below
array(
(int)0=>array(
'User' => array(
'PostType' => array(
'PHP' => array(
'id' => '2',
'type_title' => 'Core Questions',
'type_description' => 'none',
'type_sort_order' => '7'
'Post'=>array(
......
),
),
'ASP' => array(
'id' => '1',
'type_title' => 'Core Questions',
'type_description' => 'none',
'type_sort_order' => '1'
'Post'=>array(
......
),
),
),
)));
I have fetched a user with its post categorized by postType
postType has type_sort_order field
I want to sort sub array PostType by type_sort_order field
so that ASP come before PHP
I tried usort as below
usort($arr,function(){
return ($a[0]['User']['PostType']['post_sort_order'] < $b[0]['User']['PostType']['post_sort_order'])?1:-1;
});
and also many other sort but not getting correct result
array_multisort will work. Solution as follows:
$list = //Your array
$sortOrders = array();
foreach ($list[0]['User']['PostType'] as $postType) {
$sortOrders[] = $postType['type_sort_order'];
}
array_multisort($sortOrders, $list[0]['User']['PostType']);
This will grab all the sort orders in an array ordered the same as your starting array. Using array_multisort on both arrays will sort the first array, and also apply that new order to the second array, giving you the result you're after.
Your looking for http://php.net/manual/en/function.array-multisort.php
Loop though PostType and take all type_sort_order and place in a seperate array. then use that array as an argument for array_multi_sort
it seems you are just trying to sort the sub array PostType so just pass that array
got a multidimensional array and a string in a config and i need to transform it as an array key without the use of eval. Real world use of this problems is that i got a big document from mongodb that is transformed into multi dimensional array. However i need to define specific array nodes from a config file.
the idea is to create a config file as representation of the array key's hierarchy
on the config.ini the values below are some example.
colorattribute = attribute.color
wholesaleprice = prices.wholesale
Example Response from mongoDb
<?php
$products = array(
'product_name' => 'iTouch',
'brand_name' => 'Apple',
'attributes' => array ( 'color' => 'black',
'size' => '5 in'
),
'prices' => array(
'wholesale' => 135,
'retail' => 200,
),
);
function recurseKeys(array $keys,array $array){
$key = array_shift($keys);
if(!isset($array[$key])) return null;
return empty($keys) ?
$array[$key]:
recurseKeys($keys,$array[$key];
}
var_dump(recurseKeys(explode('.',$testConfig),$products);
I have an array that looks like this:
Array([0]=>Array([id]=>7 [name]=foo) [1]=>Array([id]=>10 [name]=bar) [2]=>Array([id]=>15 [name]=baz))
Each index contains an another array with various elements including an 'id'. I would like to "go up" a level, such that my top-level array is indexed by the ID element of the corresponding nested arrays, but that index still contains an array with all of the elements that were in the sub arrays?
In other words, how can I use PHP to turn the above array into this:
Array([7]=>Array([id]=>7 [name]=foo) [10]=>Array([id]=>10 [name]=bar) [15]=>Array([id]=>15 [name]=baz))
What you need to do here is extract the ids from each sub-array in your input. If you have these as an array of ids, you are just an array_combine call away from re-indexing your original array to use these ids as the keys.
You can produce such an array of ids using array_map, which leads to:
// input data
$array = array(array('id' => '7', 'name' => 'foo'),array('id' => 10, 'name' => 'bar'));
// extract ids from the input array
$ids = array_map(function($arr) { return $arr['id']; }, $array);
// "reindex" original array using ids as array keys, keep original values
$result = array_combine($ids, $array);
print_r($result);
The syntax I 've used for the anonymous function (first argument to array_map) requires PHP >= 5.3, but you can achieve the same (although a bit less conveniently) with create_function in any PHP version you 'd not be ashamed of using.
See it in action.
In modern, supported versions of PHP, this whole task can be achieved with array_column() alone.
Using null as the second parameter will leave the rows unchanged.
Using id as the 3rd parameter will assign those columnar values as the new first level keys. Be aware that if these columnar values are not unique, subsequently encountered duplicates will overwrite previously encountered rows with the same id value -- this is because keys cannot be duplicates on a given level in an array.
DO NOT bother calling array_combine(), it is simply unnecessary/indirect.
Code: (Demo)
$array = [
['id' => 7, 'name' => 'foo'],
['id' => 10, 'name' => 'bar'],
['id' => 15, 'name' => 'baz'],
];
var_export(
array_column($array, null, 'id')
);
Output:
array (
7 =>
array (
'id' => 7,
'name' => 'foo',
),
10 =>
array (
'id' => 10,
'name' => 'bar',
),
15 =>
array (
'id' => 15,
'name' => 'baz',
),
)
Try this:
$newArray = array();
foreach($oldArray as $key => $value) {
$newArray[$value['id']] = $value;
}
Since PHP 5.5.0, you can shorten the code by using array_column() instead of array_map().
$result = array_combine(array_column($array, 'id'), $array);
What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.