Change index order in array - php

Been kind of stuck on this one for a while now, so any help would be appreciated. I have one array (left) that contains a list of elements, the goal is to sort another arrays (right) keys with the values from the left array.
The left array
Array
(
[0] => ID
[1] => FirstName
[2] => LastName
[3] => Address
)
The right array
Array
(
[0] => Array
(
[FirstName] => Pim
[Address] => Finland
[LastName] => Svensson
[ID] => 3
)
[1] => Array
(
[FirstName] => Emil
[Address] => Sweden
[LastName] => Malm
[ID] => 5
)
)
What I'm trying to accomplish would be similar to this
Array
(
[0] => Array
(
[ID] => 3
[FirstName] => Pim
[LastName] => Svensson
[Address] => Finland
)
Anyone? :)
Oh, I'm running php 5.3, if it helps!

$output = array();
foreach ( $right as $array ) {
foreach ( $left as $field ) {
$temp[$field] = $array[$field];
}
$output[] = $temp;
}

You can use uksort() which lets you sort array keys by a user defined function. E.g.:
function sort_by_array($array) {
// create a sorting function based on the order of the elements in the array
$sorter = function($a, $b) use ($array) {
// if key is not found in array that specifies the order, it is always smaller
if(!isset($array[$a])) return -1;
if($array[$a] > $array[$b]) {
return 1;
}
return ($array[$a] == $array[$b]) ? 0 : -1;
};
return $sorter;
}
// $array contains the records to sort
// $sort_array is the array that specifies the order
foreach($array as &$record) {
uksort($record, sort_by_array(array_flip($sort_array)));
}
I make use of the possibility in 5.3 to define functions dynamically and I use array_flip() to transform:
Array
(
[0] => ID
[1] => FirstName
[2] => LastName
[3] => Address
)
to
Array
(
[ID] => 0
[FirstName] => 1
[LastName] => 2
[Address] => 3
)
This makes it easier to compare the keys later.

You must explode the array
Store the array in a variable like this
$array = Array
(
[0] => Array
(
[ID] => 3
[FirstName] => Pim
[LastName] => Svensson
[Address] => Finland
);
and then explode the array
after exploding the array you will get the parameters of the array seperated then you can use implode function the arrange them in anyorder as you wish

I'd take a step back and look at what you really need to do. The array is associative, so you can access the correct element instantly, right? So you don't really need it to be in order, unless you print output with foreach.
I'd suggest one of the following solutions:
If you need the "right" array to be in key-order, then look at the database query / similar and select the columns in the order you need them.
Foreach person you want to print, look up the order in the "left" array, then print the corresponding value of that key in the "right" array.

Well, your question it's uncommon, usually the associative arrays are used to resolve any problems about "position".
Anyway, there are many way to do what you are looking for what are you looking for.
You can use list() but it's position based:
foreach($oldArray as $o)
{
list($firstName,$lastName,$address,$id)=$oldArray;
$newArray[]=array($id,$firstName,$lastName,$address);
}
But the best way to solve your problem it's fill the array directly in the right order instead of re-sort after :)

Related

checking condition in multi dimensional array

I want to check a multi dimensional array for a key value and print its parent array's another key value. This might confuse a bit. But the below example can make it clear. I have a array like this.
Entity Response : Array
(
[0] => Array
(
[type] => FieldTerminology
[relevance] => 0.709023
[count] => 4
[text] => domain name
)
[1] => Array
(
[type] => Company
[relevance] => 0.603375
[count] => 2
[text] => Laravel
)
[2] => Array
(
[type] => Person
[relevance] => 0.548389
[count] => 1
[text] => M. Naveen Kumar
)
I want to check if any array has a key [type] and its value = "Person" , then i want to get its value of the key[text]. In this case I want to print M. Naveen Kumar
You can traverse the array to find it. you can use foreach(), array_walk() and so on.
$o = [];
array_walk($array, function($v) useļ¼ˆ&$o){$v['type'] == 'Person' ? $o[] = $v['text'] : '';});
var_dump($o);
Try this
$people = array_filter($array, function($each) { return $each['type'] == 'Person'; });
$names = array_map(function($each) { return $each['name']; }, $people);
How does this work step by step?
Filter the array by type using array_filter
Then map to names using array_map

Setting an array item's value as the parent array's key (PHP) [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I have an array of array that looks like this:
Array
(
[0] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[1] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[2] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
I want to set the key of the parent array with the value of id, so the result array looks like this:
Array
(
[I100] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[I101] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[I245] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
If possible I'd like to avoid using an additional loop to go through the array and creating a new array to store each item with the proper key, as the array can have thousands of items.
Thanks in advanced!
Despite your caveat, a loop is the obvious solution:
$newArray = [];
foreach($oldArray as $item)
$newArray[$item['id']] = $item;
If the problem you have is not specifically with a loop, but rather creating a copy of the array is causes excessive memory consumption, then you can edit the array in place, with a for loop:
for($i=0; $i<count($oldArray); $i++){
$oldArray[$oldArray[$i]['id']] = $oldArray[$i];
unset($oldArray[$i]);
}
Note this works because the id elements are alphanumeric strings, if they where simple integars then the above code could overwrite sections.
The only other solution is to build the correct array in the 1st place, in a similar manner.
For example, using PDO::fetch instead of PDO::fetchAll:
//$newArray = $sth->fetchAll(PDO::FETCH_ASSOC);
$newArray = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$newArray[$row['id']] = $row;
You can't overwrite keys while iterating through an array "on the fly". So here is solution with array_map which produces an array with needed structure:
// assuming $arr is your initial array
$result = [];
array_map(function($a) use (&$result){
$result[$a['id']] = $a;
}, $arr);
// $result contains the needed array
You can add needed key during creation of this array.

I want to add sub arrays to one single array keep id and value in php

My input array :
Array
(
[0] => Array
(
[id] => 1
[status_name] => Released
)
[1] => Array
(
[id] => 2
[status_name] => Under Construction
)
)
I want the output result :
Array (
[1] => Released
[2] => Under Construction
)
USe sub array id as output array key value and status_name as value array.
This is built into php as array_column. You would have:
$status_names = array_column($data, 'status_name', 'id');
print_r($status_name);
Bonus points on question as I had no idea this existed until looking for an answer for you.
Try the following:
function reOrderArray($input_array)
{
$result = array();
foreach ($input_array as $sub_array)
{
$result[$sub_array['id']] = $sub_array['status_name'];
}
return $result;
}
There might be a built-in php function to do this, array functions in php are quite powerful. I am, however, woefully unaware of one.

making array unique with only one value same

I have a array of kind
Array
(
[1] => Array
(
[id] => 1
[username] => test1
[case1] => abc
[case2] => zxc
)
[0] => Array
(
[id] => 1
[username] => test1
[case1] => fdg
[case2] => tyy
)
)
As you can see only id and username is same rest are different. Now i want to make it unique. That if only id is same in inner arrays then also only one value should come either of both.
Can any one tell me how to do this?
Any help will be highly appreciated.
Using the unique data as keys makes this easy:
$unique = array();
foreach ($array as $item) {
$unique[$item['id']] = $item;
}
create a new array in which to push the inner arrays if there is no duplicate
Use this for finding & removing specific unique in array array_unique
You should use 'id', as key for your top array (or 'username'?).

Reformat a simple PHP array

How do I go about reformatting an object?
Array
(
[0] => Array
(
[user_id] => 5
[first_name] => Ace
[last_name] => Black
)
[1] => Array
(
[user_id] => 6
[first_name] => Gary
[last_name] => Surname
)
[2] => Array
(
[user_id] => 7
[first_name] => Alan
[last_name] => Person
)
)
I need to reformat this so the user_id name is changed to just 'id' and the first_name and last_name values are merged into a single value called 'name' so the final result would look like:
Array
(
[0] => Array
(
[id] => 5
[name] => Ace Black
)
)
You might find array_map useful for this
function fixelement($e)
{
//build new element from old
$n=array();
$n['id']=$e['user_id'];
$n['name']=$e['first_name'].' '.$e['last_name'];
//return value will be placed into array
return $n;
}
$reformatted = array_map("fixelement", $original);
As you can see, one downside is that this approach constructs a second copy of the array, but having written the callback, you can always use it 'in place' like this:
foreach($original as $key=>$value)
{
$original[$key]=fixelement($value);
}
If you want to do it in place:
Foreach that array, set the keys to the values you want, unset the keys for the values you no longer want.
If you want a copy of it:
Foreach that array and ETL (extract, transform, load) into another similar array.
If you need further details to help let me know.

Categories