How to push hash into array of hash in php? - php

Like array_push() where we can push an element in to array. I want to push an hash [name,url] in to an array of hash.

If you're referring to associative arrays where the key is user-provided (rather than an auto-incrementing numeric field), just use direct syntax:
$a = Array();
$a['name'] = 'url';
Note that $a = Array(); array_push($a, 'lol'); is (almost) the same as $a = Array(); $a[] = 'lol';. array_push is just a (pointless) "shortcut" for the same syntax, which only works for automatic, numeric indexes.
I strongly recommend reading the PHP manual section on the topic. That's what it's there for.

I do not know, what do you need, but it you need to push pair of values into array, this may be your solution:
$hashes_array = array();
array_push($hashes_array, array(
'name' => 'something1',
'url' => 'http://www1',
));
array_push($hashes_array, array(
'name' => 'something2',
'url' => 'http://www2',
));
After that $hashes_array should look like that (each element of the bigger array is array itself - associative array with two keys and two values corresponding to them):
[
['name' => 'something1', 'url' => 'http://www1'],
['name' => 'something2', 'url' => 'http://www2']
]

<?php
$aArrayOfHash['example'] = 'http://example.com/';
?>

ifif i understand your problem, you want to retrieve hash value from a url then use parse_url with PHP_URL_FRAGMENT argument
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_FRAGMENT);
will return
[fragment] => anchor
Reference

Related

Associative array (PHP)

I do not know what does it mean when it says: (it is from hook_block_view code for drupal)
$block['content'] = array(
'#theme' => 'node_recent_block',
'#nodes' => $nodes,
);
I know $block['content'] is an associative array, also I know that $node is Full node object, Contains data that may not be safe.But about #theme, #nodes and 'node_recent_block.
Can someone please tell me what do they mean.
I searched a lot but I did not find out what does it mean when there is a # before name of a key.
Thank you
$block is an associative array, in which the element "content" is also an associative array.
Another way to define this would be:
$block = array(
'content' => array(
'#theme' => 'node_recent_block',
'#nodes' => $nodes,
),
);
Inside an associative array => is an assignment.
'content' is an array where '#theme' = 'node_recent_block' and '#nodes' = $nodes
Edit:
You could also assign the values like this:
$block['content']['#theme'] = 'node_recent_block';
$block['content']['#nodes'] = $nodes;

pushing and apending arrays into an associative array in php

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);

Compare associative array with simple array in php

I have a simple session array and I'm pushing page titles in it, as strings:
$_SESSION['sesArray'][] = $pageTitle;
and another predefined associative array with page titles and links:
$assoc=array(array('title' => 'page title', 'link' => 'page link'));
The session array gets flooded with titles so I'm taking out duplicates:
$array1 = array_unique($_SESSION['sesArray']);
My question is: how can I compare the $assoc array against $array1 to check for page titles that exist in both and eliminate them, ending up with another array that contains unique titles along with the link?
I have tried using:
$result= array_diff_key($assoc, $array1 );
But some duplicate titles are indeed removed and some are not.
Any ideas?
ETA data:
$array1= array('Museum', 'Club');
$assoc= array(array('title' => 'Museum', 'link' => 'museum.php' ),
array('title' => 'club', 'link' => 'club.php'));
You are not really doing a diff because an array of arrays is by definition going to have nothing in common with an array of scalars. What you need to do is filter $assoc based on the contents of $array1. Try this:
$array1= array('Museum','Club');
$assoc= array(array('title' => 'Museum', 'link' => 'museum.php' ),
array('title' => 'club', 'link' => 'club.php'));
$fn = function($arr) use ($array1) {
return !in_array($arr['title'], $array1);
};
$result =array_filter($assoc, $fn);
Ah, the infamous tech-interview problem ("compare 2 arrays and to find common entries").
try something along the lines of:
$ass = array_keys($assoc);
foreach($ass as $a)
{
while (isset($_SESSION['sesArray'][$a]))
{
unset($_SESSION['sesArray'][$a]);
}
}
The way PHP associates its tuple arrays allows you to avoid the ugly O(n^2) complexity of this issue.

Reorganize an array by 'id' index of nested arrays

I have an array that looks like this:
Array([0]=>Array([id]=>7 [name]=foo) [1]=>Array([id]=>10 [name]=bar) [2]=>Array([id]=>15 [name]=baz))
Each index contains an another array with various elements including an 'id'. I would like to "go up" a level, such that my top-level array is indexed by the ID element of the corresponding nested arrays, but that index still contains an array with all of the elements that were in the sub arrays?
In other words, how can I use PHP to turn the above array into this:
Array([7]=>Array([id]=>7 [name]=foo) [10]=>Array([id]=>10 [name]=bar) [15]=>Array([id]=>15 [name]=baz))
What you need to do here is extract the ids from each sub-array in your input. If you have these as an array of ids, you are just an array_combine call away from re-indexing your original array to use these ids as the keys.
You can produce such an array of ids using array_map, which leads to:
// input data
$array = array(array('id' => '7', 'name' => 'foo'),array('id' => 10, 'name' => 'bar'));
// extract ids from the input array
$ids = array_map(function($arr) { return $arr['id']; }, $array);
// "reindex" original array using ids as array keys, keep original values
$result = array_combine($ids, $array);
print_r($result);
The syntax I 've used for the anonymous function (first argument to array_map) requires PHP >= 5.3, but you can achieve the same (although a bit less conveniently) with create_function in any PHP version you 'd not be ashamed of using.
See it in action.
In modern, supported versions of PHP, this whole task can be achieved with array_column() alone.
Using null as the second parameter will leave the rows unchanged.
Using id as the 3rd parameter will assign those columnar values as the new first level keys. Be aware that if these columnar values are not unique, subsequently encountered duplicates will overwrite previously encountered rows with the same id value -- this is because keys cannot be duplicates on a given level in an array.
DO NOT bother calling array_combine(), it is simply unnecessary/indirect.
Code: (Demo)
$array = [
['id' => 7, 'name' => 'foo'],
['id' => 10, 'name' => 'bar'],
['id' => 15, 'name' => 'baz'],
];
var_export(
array_column($array, null, 'id')
);
Output:
array (
7 =>
array (
'id' => 7,
'name' => 'foo',
),
10 =>
array (
'id' => 10,
'name' => 'bar',
),
15 =>
array (
'id' => 15,
'name' => 'baz',
),
)
Try this:
$newArray = array();
foreach($oldArray as $key => $value) {
$newArray[$value['id']] = $value;
}
Since PHP 5.5.0, you can shorten the code by using array_column() instead of array_map().
$result = array_combine(array_column($array, 'id'), $array);

Need help about array

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.

Categories