Reorder an array from it's default order - php

I have an array that comes in this way since it's generated this way, and it's a heck of a task to change the way it's generated. This is part of it, there loads more.
$name['Age'] = '25';
$name['Location'] = 'Seattle';
$name['Last'] = 'Gates';
$name['First'] = 'Bill';
print_r($name);
How can I change it's order to something like below once it's generated?
$name['First'] = 'Bill';
$name['Last'] = 'Gates';
$name['Age'] = '25';
$name['Location'] = 'Seattle';
print_r($name);

Yes, there's a function that lets you reorder the associative array by keys according to your own criteria. It's called uksort:
$key_order = array_flip(['First', 'Last', 'Age', 'Location']);
uksort($name, function($key1, $key2) {
return $key_order[$key1] - $key_order[$key2];
});
print_r($name);
Demo.
Having said all that, I can't help wondering ain't you need something different instead: changing the order of output of your array only. For example:
$output_order = ['First', 'Last', 'Age', 'Location'];
foreach ($output_order as $key) {
echo $key, ' => ', $name[$key], PHP_EOL;
}

Related

php create arrays dynamically and merge

I'm trying to create an unknown number of arrays dynamically inside a foreach loop, merge them all at the end into one array, and use this in a JSON format for Google Analytics.
So far I have the following code which is throwing an error at the merge part:
$p=1;
foreach(...){
...
$arr = 'arr'.$p;
$name = $order->ProductGroupName;
$name = str_replace("'", "", $name);
$arr = array(
"name"=>$name,
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
for ($q = 1; $q<$p; $q++){
$arry = 'arr'.$q;
$merge = array_merge($arry, $merge);
};
How do I create the arrays dynamically and merge them at the end, please?
I'm relatively new to PHP and have tried my best to get this to work.
I think I understand what you're trying to do. Just dynamically append [] to the array and you don't need to merge:
foreach($something as $order) {
$arr[] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
}
If you want to have string keys for whatever reason, then:
$p = 1;
foreach($something as $order) {
$arr["SomeText$p"] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
And that's it. Check with:
print_r($arr);
Things like $arry = 'arr'.$q; stink of variable variables (though not done correctly) and shouldn't be used.

Get array value based on variable and indexes as string

I'm trying to execute variable which part of it is a string.
Here it is:
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
I tried to do it in following ways:
// #1
$myValue = $row{$pattern};
// #2
$myValue = eval("$row$pattern");
I also trying to get it working with variable variable, but not successful.
Any tips, how should I did it? Or myabe there is other way. I don't know how may look array, but I have only name of key indexes (provided by user), this is: index_1, index_2
You could use eval but that would be quite risky since you say the values come from user input. In that case, the best way might be to parse the string and extract the keys. Something like this should work:
$pattern = "['index_1']['index_2']";
preg_match('/\[\'(.*)\'\]\[\'(.*)\'\]/', $pattern, $matches);
if (count($matches) === 3) {
$v = $row[$matches[1]][$matches[2]];
var_dump($v);
} else {
echo 'Not found';
}
This can help -
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
$pattern = explode("']['", $pattern); // extract the keys
foreach($pattern as $key) {
$key = str_replace(array("['", "']"), '', $key); // remove []s
if (isset($row[$key])) { // check if exists
$row = $row[$key]; // store the value
}
}
var_dump($row);
Storing the $row in temporary variable required if used further.
Output
string(8) "my-value"
If you always receive two indexes then the solution is quite straight forward,
$index_1 = 'index_1';// set user input for index 1 here
$index_2 = 'index_2';// set user input for index 2 here
if (isset($row[$index_1][$index_2])) {
$myValue = $row[$index_1][$index_2];
} else {
// you can handle indexes that don't exist here....
}
If the submitted indexes aren't always a pair then it will be possible but I will need to update my answer.
As eval is not safe, only when you know what you are ding.
$myValue = eval("$row$pattern"); will assign the value you want to $myValue, you can add use return to make eval return the value you want.
here is the code that use eval, use it in caution.
demo here.
<?php
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = 'return $row[\'index_1\'][\'index_2\'];';
$myValue = eval($pattern);
echo $myValue;

Official way to find an element in a php bidimensional array?

Looking at the code above...
$Array = array(array("name"=>"Mickey","type"=>"mouse"),array("name"=>"Donald","type"=>"duck"),array("name"=>"Little Helper","type"=>"eniac"));
$search = "Donald";
foreach($Array as $Item){
if($Item["name"]==$search) $MyItem = $Item;
}
echo('The item named "'.$search.'" is '.$MyItem["type"]);
... I have the feeling that there is an array function or a better way to find an item inside a bidimensional array. These arrays are like a table. Maybe setting the keys as the index unique values (in this case, the name), but I don't know how to do either.
Using the new array_column() function in PHP 5.5
$Array = array(array("name"=>"Mickey","type"=>"mouse"),array("name"=>"Donald","type"=>"duck"),array("name"=>"Little Helper","type"=>"eniac"));
$search = "Donald";
$key = array_search(
$search,
array_column($Array,'name')
);
if($key !== false) {
$MyItem = $Array[$key];
echo('The item named "'.$search.'" is '.$MyItem["type"]);
}
If you can recompose the array as:
array("Mickey"=>"mouse","Donald"=>"duck","Little Helper"=>"eniac");
or
array("Mickey"=>array("name"=>"mouse"),"Donald"=>array("name"=>"duck"),"Little Helper"=>array("name"=>"eniac"));
and just return by key
Works for this case:
echo array_column($Array, 'type', 'name')[$search];
Or with check:
$names = array_column($Array, 'type', 'name');
echo isset($names[$search]) ? $names[$search] : 'not found';
To convert to name => type use:
$Array = array_column($Array, 'type', 'name');
Then after you can just use $Array[$search].

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

Better way to unset multiple array elements

The deal here is that I have an array with 17 elements. I want to get the elements I need for a certain time and remove them permanently from the array.
Here's the code:
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
unset($post['name']);
unset($post['email']);
unset($post['address']);
unset($post['telephone']);
unset($post['country']);
Yes the code is ugly, no need to bash. How do I make this look better?
Use array_diff_key to remove
$remove = ['telephone', 'country'];
$remaining = array_diff_key($post, array_flip($remove));
You could use array_intersect_key if you wanted to supply an array of keys to keep.
It looks like the function extract() would be a better tool for what you're trying to do (assuming it's extract all key/values from an array and assign them to variables with the same names as the keys in the local scope). After you've extracted the contents, you could then unset the entire $post, assuming it didn't contain anything else you wanted.
However, to actually answer your question, you could create an array of the keys you want to remove and loop through, explicitly unsetting them...
$removeKeys = array('name', 'email');
foreach($removeKeys as $key) {
unset($arr[$key]);
}
...or you could point the variable to a new array that has the keys removed...
$arr = array_diff_key($arr, array_flip($removeKeys));
...or pass all of the array members to unset()...
unset($arr['name'], $arr['email']);
There is another way which is better then the above examples.
Source: http://php.net/manual/en/function.unset.php
Instead of looping thorough the entire array and unsetting all its keys, you can just unset it once like so:
Example Array:
$array = array("key1", "key2", "key3");
For the entire array:
unset($array);
For unique keys:
unset($array["key1"]);
For multiple keys in one array:
unset($array["key1"], $array["key2"], $array["key3"] ....) and so on.
I hope this helps you in your development.
I understand this question is old, but I think an optimal way might be to do this:
$vars = array('name', 'email', 'address', 'phone'); /* needed variables */
foreach ($vars as $var) {
${$var} = $_POST[$var]; /* create variable on-the-fly */
unset($_POST[$var]); /* unset variable after use */
}
Now, you can use $name, $email, ... from anywhere ;)
NB: extract() is not safe, so it's completely out of question!
<?php
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
$myArray = array_except($post, ['name', 'email','address','telephone','country']);
print_r($myArray);
function array_except($array, $keys){
foreach($keys as $key){
unset($array[$key]);
}
return $array;
}
?>
In php unset function can take multiple arguments
$test = ['test1' => 1, 'test2' => 4, 'test34' => 34];
unset($test['test1'], $test['test34']);
Here is this description from documentation
unset(mixed $var, mixed ...$vars): void

Categories