Drupal/PHP - Get a specific value in an array - php

Hi
Suppose I have the code below:
[taxonomy] => Array
(
[118] => stdClass Object
(
[tid] => 118
[vid] => 4
[name] => A
[description] =>
[weight] => 4
)
[150] => stdClass Object
(
[tid] => 150
[vid] => 5
[name] => B
[description] =>
[weight] => 0
)
)
How can I only get the tid number and exclude others, could someone please give me a suggestion?
Thanks you

Assuming taxonomy is key of array $arr, You can fetch tid as,
for example ,
$key = your key //the key for which you want fetch record
$arr['taxonomy'][$key]->tid;
For getting all tid values,
$result = array();
foreach($arr['taxonomy'] as $key=>$value)
{
$value = (array)$value;
if(array_key_exists('tid'), $value)
{
$result[] = $value['tid'];
}
}
print_r($result);

$tids = array_keys($yourArray);
This works because the first level key and the values of subkey "tid" are the same.

Charles Yeung you're requirements aren't clear, you say in the other answer (for Nik) that the taxonomy id is dynamic, equally it seems you have more than one taxonomy node, so can I assume you just want return an array of tid values, right?
Equally you said to rik that you want to check if the key=value, I've no idea what you mean by that, but perhaps you could start here...
$tid=array();
foreach($taxonomy as $key=>$value) {
$tid[]=$value->tid;
}
print_r($tid);
This will give you an array of tid values, if you want to put a condition in there to constrain your output then feel free to do so, problem is your explanation of your requirements aren't clear.

Related

Extract multidimensional array values

I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.
I need to be able to extract the values and place them in strings, for example,
$uuid =
and so on.
I can't seem to find a similar query and have tried so many variations. Many thanks in advance.
Array
(
[action] => edit
[data] => Array
(
[row_204] => Array
(
[UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
[userID] => 7
[maxPoints] => 7
[awardedPoints] => 6
[Date] => 2017-06-08
)
)
)
If you know there is always only one row_* item in that array, you can just pull the first item (i.e., the only one in your case) off the front of the list with array_shift():
$data = array_shift($array['data']);
print_r($data);
Will give you:
Array (
[UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
[userID] => 7
[maxPoints] => 7
[awardedPoints] => 6
[Date] => 2017-06-08
)
Then you can just deference the keys you want:
$uuid = $data['UUID'];
The easiest would probably be:
$data = current($_POST['data']);
Then just echo $data['UUID'];.
If you need the key for whatever reason:
list($key, $data) = each($_POST['data']);

Sort an array according to a set of values from another array

I am aware there is another question on SO which is supposed to answer the same thing. My problem is that I don't see what array merge has do do with anything. I don't want to merge the arrays necessarily and I don't understand how that would help ordering them ... also I don't understand where the ordering is coming into it.
If it is relevant could someone please explain in a bit more detail whether the other answer would work for me or not and how
Here is what I have ( the array is quite large so this is a simplification )
Essentially I have something like this
Array (
[0] => stdClass Object (
[term_id] => 72
[name] => name
[slug] => slug
[term_group] => 0
[term_order] => 1
[term_taxonomy_id] => 73
[taxonomy] => gallery_category
[description] => description
[parent] => 78
[count] => 85 )
[1] => stdClass Object (
[term_id] => 77
[name] => name
[slug] => slug
etc, etc, etc, there are a lot of objects in the array
Then I have an ordering array like
Array (
[0] => 77,
[1] => 72,
etc
So what I want to do is to impose the ordering of the second array on the first one - the ordering array holds the value of the [term_id] from the second array in the corrrect order. In the example above that would mean that I would reverse the order of the first two objects.
$order_array = [77, 72];
$order_array = array_flip($order_array);
usort($objects, function($a, $b) use ($order_array)
{
return $order_array[$a->term_id] - $order_array[$b->term_id];
});
This assumes that $order_array has an entry for every term_id.
uksort could do it.
function cmp($a, $b)
{
$ordering_array=array(0=>77, 1=>72);
return $ordering_array[$a] - $ordering_array[$b];
}
$a = array() #etc...
uksort($a, "cmp");

PDO fetchAll() primary key as array group key

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).
My current code:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
Which then outputs:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.
Is it possible for me to group each array by their primary key (which is id)?
You can just use
$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))
PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.
This should yield what you are looking for :
$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:
$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
$Array[$d['id']]["id"] = $d['id'];
$Array[$d['id']]["name"] = $d['name'];
$Array[$d['id']]["path"] = $d['path'];
}
// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) )
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.
I'd like to point out the only solution that works for me:
fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
Beware that this will strip the first column from the resultset. So the query must be:
SELECT id_keyname AS arrkey, id_keyname, .... FROM ...
I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.
The code(in human readable form) will be:
$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) {
$temp2 = $temp['id'];
unset($temp['id']);
$returnArray[$temp2] = $temp;
return $returnArray;
}
);
So, my question is; is it possible for me to group each array by their
primary key (which is id)
Off course, you have 2 options here: Either to change the query or parse a result-set.
So, I'm sure you don't want to change query itself, so I'd go with parsing result-set.
Note:
You should use prepared SQL statements when they make sense. If you want to bind some parameters then its OKAY. But in this case, you only want get get result-set, so prepare() and fetch() will be kinda overdo.
So, you have:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
And you want:
Array( [id] => Array('bar' => 'foo') ....)
Well, you can do something like this:
$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();
foreach($stmt as $array){
$result[$array['id']] = $array;
}
print_r($result); // Outputs: Array(Array('id' => Array(...)))

making array unique with only one value same

I have a array of kind
Array
(
[1] => Array
(
[id] => 1
[username] => test1
[case1] => abc
[case2] => zxc
)
[0] => Array
(
[id] => 1
[username] => test1
[case1] => fdg
[case2] => tyy
)
)
As you can see only id and username is same rest are different. Now i want to make it unique. That if only id is same in inner arrays then also only one value should come either of both.
Can any one tell me how to do this?
Any help will be highly appreciated.
Using the unique data as keys makes this easy:
$unique = array();
foreach ($array as $item) {
$unique[$item['id']] = $item;
}
create a new array in which to push the inner arrays if there is no duplicate
Use this for finding & removing specific unique in array array_unique
You should use 'id', as key for your top array (or 'username'?).

Change index order in array

Been kind of stuck on this one for a while now, so any help would be appreciated. I have one array (left) that contains a list of elements, the goal is to sort another arrays (right) keys with the values from the left array.
The left array
Array
(
[0] => ID
[1] => FirstName
[2] => LastName
[3] => Address
)
The right array
Array
(
[0] => Array
(
[FirstName] => Pim
[Address] => Finland
[LastName] => Svensson
[ID] => 3
)
[1] => Array
(
[FirstName] => Emil
[Address] => Sweden
[LastName] => Malm
[ID] => 5
)
)
What I'm trying to accomplish would be similar to this
Array
(
[0] => Array
(
[ID] => 3
[FirstName] => Pim
[LastName] => Svensson
[Address] => Finland
)
Anyone? :)
Oh, I'm running php 5.3, if it helps!
$output = array();
foreach ( $right as $array ) {
foreach ( $left as $field ) {
$temp[$field] = $array[$field];
}
$output[] = $temp;
}
You can use uksort() which lets you sort array keys by a user defined function. E.g.:
function sort_by_array($array) {
// create a sorting function based on the order of the elements in the array
$sorter = function($a, $b) use ($array) {
// if key is not found in array that specifies the order, it is always smaller
if(!isset($array[$a])) return -1;
if($array[$a] > $array[$b]) {
return 1;
}
return ($array[$a] == $array[$b]) ? 0 : -1;
};
return $sorter;
}
// $array contains the records to sort
// $sort_array is the array that specifies the order
foreach($array as &$record) {
uksort($record, sort_by_array(array_flip($sort_array)));
}
I make use of the possibility in 5.3 to define functions dynamically and I use array_flip() to transform:
Array
(
[0] => ID
[1] => FirstName
[2] => LastName
[3] => Address
)
to
Array
(
[ID] => 0
[FirstName] => 1
[LastName] => 2
[Address] => 3
)
This makes it easier to compare the keys later.
You must explode the array
Store the array in a variable like this
$array = Array
(
[0] => Array
(
[ID] => 3
[FirstName] => Pim
[LastName] => Svensson
[Address] => Finland
);
and then explode the array
after exploding the array you will get the parameters of the array seperated then you can use implode function the arrange them in anyorder as you wish
I'd take a step back and look at what you really need to do. The array is associative, so you can access the correct element instantly, right? So you don't really need it to be in order, unless you print output with foreach.
I'd suggest one of the following solutions:
If you need the "right" array to be in key-order, then look at the database query / similar and select the columns in the order you need them.
Foreach person you want to print, look up the order in the "left" array, then print the corresponding value of that key in the "right" array.
Well, your question it's uncommon, usually the associative arrays are used to resolve any problems about "position".
Anyway, there are many way to do what you are looking for what are you looking for.
You can use list() but it's position based:
foreach($oldArray as $o)
{
list($firstName,$lastName,$address,$id)=$oldArray;
$newArray[]=array($id,$firstName,$lastName,$address);
}
But the best way to solve your problem it's fill the array directly in the right order instead of re-sort after :)

Categories