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.
Related
I'm writing a php web application where I have a nested array which looks similar to the following:
$results = array(
array(
array(
'ID' => 1,
'Name' => 'Hi'
)
),
array(
array(
'ID' => 2,
'Name' => 'Hello'
)
),
array(
array(
'ID' => 3,
'Name' => 'Hey'
)
)
);
Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.
My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.
Here is the code I have so far:
public function filterArray($results) {
$outputArray = array();
foreach ($results as $key => $row) {
}
return $outputArray;
}
Would anyone be able to suggest the most effective way to achieve what I am after?
Thanks :)
Simply use call_user_func_array as
$array = call_user_func_array('array_merge', $results);
print_r($array);
Demo
My application uses many arrays, and many sql queries. My issue is within this code:
I execute this query:
$select = "SELECT name, surname FROM table"
$query = $connection->query($select);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
Then, I pass the values into an array like this:
$array_dump= array(
array(
array('name' => 'name'),
array('content' => $array['name'])
),
array(
array('name' => 'surname'),
array('content' => $array['surname'])
),
)
In fact, this works properly, if you don't set error_reporting(). If I turn on, I get this error:
Notice: Undefined index: surname in C:\AppServ\www\test.php on line 27
This actually happens, due the array was not set. In other words, surname value is empty.
My trouble:
I must use this methodology, but I can't use something like this (got error):
array(
array('name' => 'name'),
array('content' => (isset($array['surname']) ? $array['surname'] : '')
)
My question
As you see, this ain't an error properly, but that "Notice" should not appear (as INDEX is not defined...). Is there any way to set ALL array keys by default, from that query, even if the values are NULL, such as "surname" field? That would be the fastest solution. I've been looking for this, but got no answer.
Thanks!
You should be iterating over the results and formatting them as necessary. Something like this:
$array = $query->fetchAll(PDO::FETCH_ASSOC);
$array_dump = array();
foreach ( $array as $person ) {
$tempArray = array();
array_push($tempArray, array(
'name' => 'name',
'content' => $person['name']
));
array_push($tempArray, array(
'name' => 'surname',
'content' => $person['surname']
));
array_push($array_dump, $tempArray);
}
There is no way to set ALL possible array keys by default. But you can build array of default values based on predefined set of keys and merge it with main array. Somehow like this:
$a_keys = array('name', 'surname');
$a_defaults = array_combine($a_keys, array_fill(0, count($a_keys), 0));
$array = array_merge($a_defaults, $array);
...
How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);
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'];.
I have an array of arrays like so:
array( array(), array(), array(), array() );
the arrays inside the main array contain 4 keys and their values. The keys are the same among all arrays like this:
array( 'id' => 'post_1',
'desc' => 'Description 1',
'type' => 'type1',
'title' => 'Title'
);
array( 'id' => 'post_2',
'desc' => 'Description 2',
'type' => 'type2',
'title' => 'Title'
);
So I want to create another array and extract the id and type values and put them in a new array like this:
array( 'post_1' => 'type1', 'post_2' => 'type2'); // and so on
The keys in this array will be the value of id key old arrays and their value will be the value of the type key.
So is it possible to achieve this? I tried searching php.net Array Functions but I don't know which function to use?
PHP 5.5 introduced an array function that does exactly what you want.
I'm answering this in hopes that it may help someone in future with this question.
The function that does this is array_column.
To get what you wanted you would write:
array_column($oldArray, 'type', 'id');
To use it on lower versions of PHP either use the accepted answer or take a look at how this function was implemented in PHP and use this library: https://github.com/ramsey/array_column
Just use a good ol' loop:
$newArray = array();
foreach ($oldArray as $entry) {
$newArray[$entry['id']] = $entry['type'];
}