I am trying to create the following array dynamically:
$aSettings = array( "text"=>
array( "icon_type" =>
array(
"name"=>"icon_type",
"method"=>"dropdown",
"option"=>"",
"default"=>""
),
"column" =>
array(
"name"=>"column_count",
"method"=>"dropdown",
"default"=>"1"
)
)
)
I am not sure how to declare the array into the array.
I have the following example code:
$aSettings=array();
$aSetting_type['text']=array();
$aSetting_name['icon_type']=array();
$aSetting_name['column']=array();
$aSetting_values1=array('name'=>'icon_type','method'=>'dropdown','option'=>'','default'=>'');
$aSetting_values2=array('name'=>'column_count','method'=>'dropdown','default'=>1);
I guess I am overlooking something very simple, but how do I put all these arrays into each other?
I want to be able to call a value from the array as:
$aSettings['text']['column']['name'];
Any ideas?
You could do:
$aSettings['text']['icon_type'] = $aSetting_values1;
$aSettings['text']['column'] = $aSetting_values2;
If you need it more dynamic, you could use variables like so:
$type = 'text';
$name1 = 'icon_type';
$aSettings[$type][$name1] = $aSetting_values1;
Collect the array is reverse lower to higher order, it would be easy to collect without confusions, for example
$icon_type = array(
"name"=>"icon_type",
"method"=>"dropdown",
"option"=>"",
"default"=>""
);
$column = array(
"name"=>"column_count",
"method"=>"dropdown",
"default"=>"1"
);
$text = array(
"icon_type" => $icon_type,
"column" => $column
);
$aSettings = array(
"text"=> $text
);
Once you collect array like this you can easily access any element in the array i.e. echo $aSettings['text']['column']['name'];
Related
I have different multidimensional arrays with different keys and values:
$array_1 = array('cars' => array('audi' => array('a3' => array('one', 'two', 'three'), 'a5' => array('five', 'six', 'seven')), 'mercedes' => array('type_1' => array('submodel' => array('whatever'))), 'other_cat' => array('different_things')));
then I would like to unset a specific key, for example:
unset($array_1['cars']['audi']['a5']);
Now I like to "split it up", to have the key variable.
$to_unset = ['cars']['audi']['a5'];
How can I unset that specific (variable!) key?
AƤron
An easy utility to avoid removing array keys that do not exist by accident:
function removeArrayKey($path, &$array ) {
$array_temp = &$array;
$previousItem = null;
$path_bits = explode( ".", $path );
foreach( $path_bits as &$path_bit ) {
if( !isset( $array_temp[ $path_bit ] ) ) {
die("Error" . $path_bit);
//throw new Exception( "Path does not exist in array" );
}
$previousItem = &$array_temp;
$array_temp = &$array_temp[ $path_bit ];
}
if( isset( $previousItem ) ) {
unset( $previousItem[ $path_bit ] );
}
return $array;
}
To use the function, simply use removeArrayKey( "cars.mercedes.cars", $array_1 ); and separate each array index with a .
So as i see your problem, you'd like to save your array path into a variable. You can solve this problem on two different ways:
Save every key into a variable
The way i would do it, if my array structure looks always the same (e.g. [cars][type][model]). You can save the key to delete into a variable:
$cars = 'cars';
$type = 'audi';
$model = 'a5';
unset($array_1[$cars][$type][$model]);
This will work excellent in a for(each) loop.
Saving your keys into an array
This method will save your problem, but it is not the best option. You can save all the keys you like to unset into an array. This way can cause many bugs and you should reconsider your array structure, if this way is your solution.
// arrays start at 0
$to_unset = [
0 => 'cars',
1 => 'audi',
2 => 'a5',
];
unset($array_1[$to_unset[0]][$to_unset[1]][$to_unset[2]]);
An other possible option here is to name the keys of the $to_unset array.
// arrays start at 0
$to_unset = [
'cars' => 'cars',
'type' => 'audi',
'model' => 'a5',
];
unset($array_1[$to_unset['cars']][$to_unset['type']][$to_unset['model']]);
You can probably go with eval but it's not recommended.
eval('unset($array_1' . $to_unset . ');');
I am new to using multidimensional arrays with php, I have tried to stay away from them because they confused me, but now the time has come that I put them to good use. I have been trying to understand how they work and I am just not getting it.
What I am trying to do is populate results based on a string compare function, once I find some match to an 'item name', I would like the first slot to contain the 'item name', then I would like to increment the priority slot by 1.
So when when I'm all done populating my array, it is going to have a variety of different company names, each with their respective priority...
I am having trouble understanding how to declare and manipulate the following array:
$matches = array(
'name'=>array('somename'),
'priority'=>array($priority_level++)
);
So, in what you have, your variable $matches will point to a keyed array, the 'name' element of that array will be an indexed array with 1 entry 'somename', there will be a 'priority' entry with a value which is an indexed array with one entry = $priority_level.
I think, instead what you probably want is something like:
$matches[] = array(name => 'somename', $priority => $priority_level++);
That way, $matches is an indexed array, where each index holds a keyed array, so you could address them as:
$matches[0]['name'] and $matches[0]['priority'], which is more logical for most people.
Multi-dimensional arrays are easy. All they are is an array, where the elements are other arrays.
So, you could have 2 separate arrays:
$name = array('somename');
$priority = array(1);
Or you can have an array that has these 2 arrays as elements:
$matches = array(
'name' => array('somename'),
'priority' => array(1)
);
So, using $matches['name'] would be the same as using $name, they are both arrays, just stored differently.
echo $name[0]; //'somename';
echo $matches['name'][0]; //'somename';
So, to add another name to the $matches array, you can do this:
$matches['name'][] = 'Another Name';
$matches['priority'][] = 2;
print_r($matches); would output:
Array
(
[name] => Array
(
[0] => somename
[1] => Another Name
)
[priority] => Array
(
[0] => 1
[1] => 2
)
)
In this case, could this be also a solution with a single dimensional array?
$matches = array(
'company_1' => 0,
'company_2' => 0,
);
if (isset($matches['company_1'])) {
++$matches['company_1'];
} else {
$matches['company_1'] = 1;
}
It looks up whether the name is already in the list. If not, it sets an array_key for this value. If it finds an already existing value, it just raises the "priority".
In my opinion, an easier structure to work with would be something more like this one:
$matches = array(
array( 'name' => 'somename', 'priority' => $priority_level_for_this_match ),
array( 'name' => 'someothername', 'priority' => $priority_level_for_that_match )
)
To fill this array, start by making an empty one:
$matches = array();
Then, find all of your matches.
$match = array( 'name' => 'somename', 'priority' => $some_priority );
To add that array to your matches, just slap it on the end:
$matches[] = $match;
Once it's filled, you can easily iterate over it:
foreach($matches as $k => $v) {
// The value in this case is also an array, and can be indexed as such
echo( $v['name'] . ': ' . $v['priority'] . '<br>' );
}
You can also sort the matched arrays according to the priority:
function cmp($a, $b) {
if($a['priority'] == $b['priority'])
return 0;
return ($a['priority'] < $b['priority']) ? -1 : 1;
}
usort($matches, 'cmp');
(Sourced from this answer)
$matches['name'][0] --> 'somename'
$matches['priority'][0] ---> the incremented $priority_level value
Like David said in the comments on the question, it sounds like you're not using the right tool for the job. Try:
$priorities = array();
foreach($companies as $company) {
if (!isset($priorities[$company])) { $priorities[$company] = 0; }
$priorities[$company]++;
}
Then you can access the priorities by checking $priorities['SomeCompanyName'];.
$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1
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.
I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.
So my array looks like this:
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
So I'd like to have it in the following form:
$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
"http://localhost/img/second.png" )
);
I haven't been PHP'ing for a while, but for that simple use-case I would use explode.
$array['urls'] = explode(',', $array['urls']);
Uncertain if I interpreted your question correct though?
You can use array_walk_recursive like in the following example.
function url(&$v,$k)
{
if($k=='urls') {
$v = explode(",",$v);
}
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");
You can check the output on PHP Sandbox