How to remap array keys (based on values) with PHP? - php

<?php
// get unordered array of Group objects
$groups = $this->getDoctrine()->getManager()->getRepository('AcmeDemoBundle:Group');
$array = array();
// map array to $groupName => $groupObject
foreach ($groups as $group) {
$array[$group->getName()] = $group;
}
Is there a shorter way to do that in PHP?
Note: Group names are unique, not empty strings.
I was thinking about array_walk, but I'm not sure if can replace the key somehow?

It seems there is no shorter/better way than the one posted in the question.

Related

How to combine multiple arrays

First off this question in in relation to this question. My issue is that a friend of mine has upwards of around 300 or so arrays that she needs to insert into the database. I get the database part as you notice in the question I linked I have that part down. My question however arises on just how exactly I am supposed to get all the arrays and bring them together so that I could could do a foreach on the arrays and check if a value is an array, if it is then use the arrays name as the table in the INSERT query.
This is my updated code :
$colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes
$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array
foreach ($AllArrays as $varName => $value) { // Run through all the variables set in the get_defined_vars
if(is_array($value) && $varName == 'colors') { // If it is an array and if the array is colors[] then
$Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
}
}
This will now give me access to all the data.
Here you go:
$colors['Colors_All'] = array("Black","Charcoal","Light_Gray","Silver","White","Gold","Bronze","Copper","Platinum","Navy","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Turquoise","Tiffany_Blue");
$colors['Colors_Bright_All'] = array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet");
$colors['Colors_Light_All'] = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");
// This will store the merged results of each array
$colorVars = array();
// Loop through all of the defined variables
foreach ($colors as $colorKey => $value) {
// Add the results of this array to the main $colorVars array
$colorVars = array_merge($colorVars, $value);
}

Merge multiple arrays by index

Im some array that's being returned by some query.. and the result is something like this:
array(array('balance_1'=> '-5', 'balance_2'=>'-21'), array('balance_1'=> '-21', 'balance_2'=>'21'), array('balance_1'=> '-50', 'balance_2'=>'40'))
i want to transform this into an array that looks something like this:
array(array(-5,11,-50), array(-21, 21, 40));
basicly i want to join all balance_1, all balance_2, all balance_3 into separated arrays.
any ideas? thanks
You'll just loop over the list, then collect the values. It's most simple if you reuse the existing keys to group:
foreach ($list as $row) {
foreach ($row as $key=>$value) {
$out[$key][] = $value;
}
}
This way you'll get an $out array, with [balance_1] or [balance_2] holding the value lists.
Loop though the array and use "array_key_exists" if the key exists add to the array, if it doesn't build a new array with your index.
For more can be found here:
http://www.php.net/manual/en/function.array-key-exists.php

Storing array within an array using PHP

foreach ($topicarray as $key=>$value){
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)){ extract($file);
$topicarray[$value] = array( array($id=>$title)
);
}
}
The first foreach loop is providing me with an array of unique values which forms a 1-dimensional array.
The while loop is intended to store another array of values inside the 1-dimensional array.
When the while loop returns to the beginning, it is overwriting it. So I only ever get the last returned set of values in the array.
My array ends up being a two dimensional array with only one value in each of the inner arrays.
Feels like I'm missing something very basic here - like a function or syntax which prevents the array from overwriting itself but instead, adds to the array.
Any ideas?
Step 1. Replace $topicarray[$value] with $topicarray[$value][]
Step 2. ???
Step 3. Profit
Make $topicarray[$value] an array of rows, instead of one row. Also, don't use extract here.
foreach ($topicarray as $key => $value) {
$rows = array();
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)) {
$rows[] = array($file['id'] => $file['title']);
}
$topicarray[$value] = $rows;
}
Also, you should switch to PDO or MySQLi.

Split a string to form multidimensional array keys?

I'm creating JSON encoded data from PHP arrays that can be two or three levels deep, that look something like this:
[grandParent] => Array (
[parent] => Array (
[child] => myValue
)
)
The method I have, which is simply to create the nested array manually in the code requires me to use my 'setOption' function (which handles the encoding later) by typing out some horrible nested arrays, however:
$option = setOption("grandParent",array("parent"=>array("child"=>"myValue")));
I wanted to be able to get the same result by using similar notation to javascript in this instance, because I'm going to be setting many options in many pages and the above just isn't very readable, especially when the nested arrays contain multiple keys - whereas being able to do this would make much more sense:
$option = setOption("grandParent.parent.child","myValue");
Can anyone suggest a way to be able to create the multidimensional array by splitting the string on the '.' so that I can json_encode() it into a nested object?
(the setOption function purpose is to collect all of the options together into one large, nested PHP array before encoding them all in one go later, so that's where the solution would go)
EDIT: I realise I could do this in the code:
$options['grandparent']['parent']['child'] = "myValue1";
$options['grandparent']['parent']['child2'] = "myValue2";
$options['grandparent']['parent']['child3'] = "myValue3";
Which may be simpler; but a suggestion would still rock (as i'm using it as part of a wider object, so its $obj->setOption(key,value);
This ought to populate the sub-arrays for you if they haven't already been created and set keys accordingly (codepad here):
function set_opt(&$array_ptr, $key, $value) {
$keys = explode('.', $key);
// extract the last key
$last_key = array_pop($keys);
// walk/build the array to the specified key
while ($arr_key = array_shift($keys)) {
if (!array_key_exists($arr_key, $array_ptr)) {
$array_ptr[$arr_key] = array();
}
$array_ptr = &$array_ptr[$arr_key];
}
// set the final key
$array_ptr[$last_key] = $value;
}
Call it like so:
$opt_array = array();
$key = 'grandParent.parent.child';
set_opt($opt_array, $key, 'foobar');
print_r($opt_array);
In keeping with your edits, you'll probably want to adapt this to use an array within your class...but hopefully this provides a place to start!
What about $option = setOption("grandParent", { parent:{ child:"myValue" } });?
Doing $options['grandparent']['parent']['child'] will produce an error if $options['grandparent']['parent'] was not set before.
The OO version of the accepted answer (http://codepad.org/t7KdNMwV)
$object = new myClass();
$object->setOption("mySetting.mySettingsChild.mySettingsGrandChild","foobar");
echo "<pre>".print_r($object->options,true)."</pre>";
class myClass {
function __construct() {
$this->setOption("grandparent.parent.child","someDefault");
}
function _setOption(&$array_ptr, $key, $value) {
$keys = explode('.', $key);
$last_key = array_pop($keys);
while ($arr_key = array_shift($keys)) {
if (!array_key_exists($arr_key, $array_ptr)) {
$array_ptr[$arr_key] = array();
}
$array_ptr = &$array_ptr[$arr_key];
}
$array_ptr[$last_key] = $value;
}
function setOption($key,$value) {
if (!isset($this->options)) {
$this->options = array();
}
$this->_setOption($this->options, $key, $value);
return true;
}
}
#rjz solution helped me out, tho i needed to create a array from set of keys stored in array but when it came to numerical indexes, it didnt work. For those who need to create a nested array from set of array indexes stores in array as here:
$keys = array(
'variable_data',
'0',
'var_type'
);
You'll find the solution here: Php array from set of keys

PHP key value pairs vs. arrays

I'm trying to pass key values pairs within PHP:
// "initialize"
private $variables;
// append
$this->variables[] = array ( $key = $value)
// parse
foreach ( $variables as $key => $value ) {
//..
}
But it seems that new arrays are added instead of appending the key/value, nor does the iteration work as expect. Please let me know what the proper way is.
Solution
$this->variables[$key] = $value;
did the trick - the iteration worked as described above.
I think you may be looking for:
$this->variables[$key] = $value;
The way you have it right now you are creating an array of arrays, so you would have to do this:
foreach($this->variables as $tuple) {
list($key, $value) = $tuple;
}
Referring to Perl, but helps understand the difference between hashes and arrays:
Some people think that hashes are like arrays (the old name 'associative array' also indicates this, and in some other languages, such as PHP, there is no difference between arrays and hashes.), but there are two major differences between arrays and hashes. Arrays are ordered, and you access an element of an array using its numerical index. Hashes are un-ordered and you access a value using a key which is a string.
Source: http://perlmaven.com/perl-hashes

Categories