Move array element by associative key to the beginning of an array - php

So far all my research has shown that this cannot be achieved without writing lengthy functions such as the solution here
Surely there is a simpler way of achieving this using the predefined PHP functions?
Just to be clear, I am trying to do the following:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
// Call some cool function here and return the array where the
// the element with key 'bla2' has been shifted to the beginning like so
print_r($test);
// Prints bla2=1234, bla=>123 etc...
I have looked at using the following functions but have so far have not been able to write a solution myself.
array_unshift
array_merge
To Summarize
I would like to:
Move an element to the beginning of an array
... whilst maintaining the associative array keys

This seems, funny, to me. But here ya go:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//store value of key we want to move
$tmp = $test['bla2'];
//now remove this from the original array
unset($test['bla2']);
//then create a new array with the requested index at the beginning
$new = array_merge(array('bla2' => $tmp), $test);
print_r($new);
Output looks like:
Array
(
[bla2] => 1234
[bla] => 123
[bla3] => 12345
)
You could turn this into a simple function that takes-in a key and an array, then outputs the newly sorted array.
UPDATE
I'm not sure why I didn't default to using uksort, but you can do this a bit cleaner:
$test = array(
'bla' => 123,
'bla2' => 1234,
'bla3' => 12345
);
//create a function to handle sorting by keys
function sortStuff($a, $b) {
if ($a === 'bla2') {
return -1;
}
return 1;
}
//sort by keys using user-defined function
uksort($test, 'sortStuff');
print_r($test);
This returns the same output as the code above.

This isn't strictly the answer to Ben's question (is that bad?) - but this is optimised for bringing a list of items to the top of the list.
/**
* Moves any values that exist in the crumb array to the top of values
* #param $values array of options with id as key
* #param $crumbs array of crumbs with id as key
* #return array
* #fixme - need to move to crumb Class
*/
public static function crumbsToTop($values, $crumbs) {
$top = array();
foreach ($crumbs AS $key => $crumb) {
if (isset($values[$key])) {
$top[$key] = $values[$key];
unset($values[$key]);
}
}
return $top + $values;
}

Related

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

Applying a variable level array to an existing array

I have two arrays, one of which is a "section" of the other. For example:
$array = array('file_name1'=>'date1',
'file_name2'=>'date2',
'file_name3'=> array('file_name3.1'=>'date3.1',
'file_name3.2'=>'date3.2'),
'file_name4'=>'date4');
$array_part = array('file_name3'=>array('file_name3.2'=>'date3.2.2'));
In my script, the first array holds a directory structure with the final values being the last-modified date. When I find a change, I want to apply the date value from the second array into the original array. Both arrays are dynamically created, so I don't know the depth of either array. How can I apply this value to the original array?
You are most likely looking for array_replace_recursive:
print_r(
array_replace_recursive($array, $array_part)
);
Which gives in your case:
Array
(
[file_name1] => date1
[file_name2] => date2
[file_name3] => Array
(
[file_name3.1] => date3.1
[file_name3.2] => date3.2.2
)
[file_name4] => date4
)
Example Code (Demo):
<?php
/**
* Applying a variable level array to an existing array
*
* #link http://stackoverflow.com/q/18519457/367456
*/
$array = array('file_name1' => 'date1',
'file_name2' => 'date2',
'file_name3' => array('file_name3.1' => 'date3.1',
'file_name3.2' => 'date3.2'),
'file_name4' => 'date4');
$array_part = array('file_name3' => array('file_name3.2' => 'date3.2.2'));
print_r(
array_replace_recursive($array, $array_part)
);
you can use php referneces
a data can be found here:
http://php.net/manual/en/language.references.pass.php
<?php
function foo(&$var)
{
$var++;
}
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
?>

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

Use an array as an index to access a multidimensional array in PHP

I am having a problem accessing an object in a multidimensional array.
THE CONTEXT
Basically, I have an object (category) which consists of Name, ID, ParentID and more. I also have an array ultimateArray which is multidimentional.
For a given category, I am writing a function (getPath()) that will return an array of ids. For example, an object named Granny Smith has a parentID of 406 and is therefore a child of Food(5) -> Fruits(101) -> Apples(406). The function will return either an array or string of the ids of the objects parents. In the above example this would be: 5 -> 101 -> 406 or ["5"]["101"]["406"] or [5][101][406]. Food is a root category!
THE PROBLEM
What I need to do is use whatever is returned from getPath() to access the category id 406 (Apples) so that I can add the object Granny Smith to the children of Apples.
The function $path = $this->getPath('406'); is adaptable. I am just having difficulty using what is returned in the following line:
$this->ultimate[$path]['Children'][]= $category;
It works when I hard code in:
$this->ultimate["5"]["101"]["406"]['Children'][]= $category;
//or
$this->ultimate[5][101][406]['Children'][]= $category;
Any help is much appreciated.
Suppose you have the array like below
<?php
$a = array(
12 => array(
65 => array(
90 => array(
'Children' => array()
)
)
)
);
$param = array(12, 65, 90); // your function should return values like this
$x =& $a; //we referencing / aliasing variable a to x
foreach($param as $p){
$x =& $x[$p]; //we step by step going into it
}
$x['Children'] = 'asdasdasdasdas';
print_r($a);
?>`
You can try referencing or aliasing it
http://www.php.net/manual/en/language.references.whatdo.php
The idea is to make a variable which is an alias of your array and going deep from the variable since we can't directly assigning multidimensional key from string (AFAIK)
output
Array
(
[12] => Array
(
[65] => Array
(
[90] => Array
(
[Children] => asdasdasdasdas
)
)
)
)
You can use a recursive function to access the members. This returns NULL if the keys do not correspond with the path, but you could also throw errors or exceptions there. Also please note that i have added "Children" to the path. I have done this so you can use this generically. I just did an edit to show you how to do it without children in the path.
<?php
$array = array(1 => array(2 => array(3 => array("Children" => array("this", "are", "my", "children")))));
$path = array(1, 2, 3, "Children");
$pathWithoutChildren = array(1, 2, 3);
function getMultiArrayValueByPath($array, $path) {
$key = array_shift($path);
if (array_key_exists($key, $array) == false) {
// requested key does not exist, in this example, just return null
return null;
}
if (count($path) > 0) {
return getMultiArrayValueByPath($array[$key], $path);
}
else {
return $array[$key];
}
}
var_dump(getMultiArrayValueByPath($array, $path));
$results = getMultiArrayValueByPath($array, $pathWithoutChildren);
var_dump($results['Children']);

Add 2 values to 1 key in a PHP array

I have a result set of data that I want to write to an array in php. Here is my sample data:
**Name** **Abbrev**
Mike M
Tom T
Jim J
Using that data, I want to create an array in php that is of the following:
1|Mike|M
2|Tom|T
3|Jim|j
I tried array_push($values, 'name', 'abbreviation') [pseudo code], which gave me the following:
1|Mike
2|M
3|Tom
4|T
5|Jim
6|J
I need to do a look up against this array to get the same key value, if I look up "Mike" or "M".
What is the best way to write my result set into an array as set above where name and abbreviation share the same key?
PHP's not my top language, but try these:
array_push($values, array("Mike", "M"))
array_push($values, array("Tom", "T"))
array_push($values, array("Jim", "J"))
$name1 = $values[1][0]
$abbrev1 = $values[1][1]
or:
array_push($values, array("name" => "Mike", "abbrev" => "M"))
array_push($values, array("name" => "Tom", "abbrev" => "T"))
array_push($values, array("name" => "Jim", "abbrev" => "J"))
$name1 = $values[1]["name"]
$abbrev1 = $values[1]["abbrev"]
The trick is to use a nested array to pair the names and abbreviations in each entry.
$person = array('name' => 'Mike', 'initial' => 'M');
array_push($people, $person);
That said, I'm not sure why you're storing the data separately. The initial can be fetched directly from the name via substr($name, 0, 1).
You will need to create a two dimensional array to store more than one value.
Each row in your result set is already an array, so it will need to be added to your variable as an array.
array_push($values, array('name', 'abbreviation'));
maybe you create a simple class for that as the abbreviation is redundant information in your case
class Person
{
public $name;
pulbic function __construct($name)
{
$this->name = (string)$name;
}
public function getAbbrev()
{
return substr($this->name, 0, 1);
}
public function __get($prop)
{
if ($prop == 'abbrev') {
return $this->getAbbrev();
}
}
}
$persons = array(
new Person('Mike'),
new Person('Tom'),
new Person('Jim')
);
foreach ($persons as $person) {
echo "$person->name ($person->abbrev.)<br/>";
}
You could use two separate arrays, maybe like:
$values_names = array();
$values_initials = array();
array_push($values_names, 'Mike');
array_push($values_initials, 'M');
array_push($values_names, 'Tom');
array_push($values_initials, 'T');
array_push($values_names, 'Jim');
array_push($values_initials, 'J');
So you use two arrays, one for each of the second and third columns using the values in the first one as keys for both arrays.
php arrays work like hash lookup tables, so in order to achieve the desired result, you can initialize 2 keys, one with the actual value and the other one with a reference pointing to the first. For instance you could do:
$a = array('m' => 'value');
$a['mike'] = &$a['m']; //notice the end to pass by reference
if you try:
$a = array('m' => 'value');
$a['mike'] = &$a['m'];
print_r($a);
$a['m'] = 'new_value';
print_r($a);
$a['mike'] = 'new_value_2';
print_r($a);
the output will be:
Array
(
[m] => value
[mike] => value
)
Array
(
[m] => new_value
[mike] => new_value
)
Array
(
[m] => new_value_2
[mike] => new_value_2
)
have to set the same value to both Mike and M for keys.

Categories