Percentages in key of an array - php

I'm currently reading through some code in a drupal module and have come across the following in an associative array.
$this->replacements = array(
'%field' => $this->instance['label'],
'%bundle' => $bundles[$this->instance['entity_type']][$this->instance['bundle']]['label'],
);
What does the % in the key mean or is it just a string label

I think its just sting label.
$a = array("%name" => "pugazh", "vaalue" => "value");
print_r($a);
If you try like this in corephp it will return an output like this
Array ( [%name] => pugazh [vaalue] => value )
But i don't know what its mean in drupal.

Related

How to Reference/pull/sort by a specific key in a multidimensional array

I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.
$arrImages[] =
[
'img_sm'=>'image1.jpg',
'tag_GlassDoor'=>0,
'tag_GlassWall'=>1,
];
$arrImages[] =
[
'img_sm'=>'image2.jpg',
'tag_GlassDoor'=>1,
'tag_GlassWall'=>1,
];
Filtering is the answer, it can be used to filter one dimensional Arrays and multidimensional arrays.
the general implementation would be something like this:
$arr = array(
array(
'image' => "data",
'hasObject' => 1
),
array(
'image' => "data",
'hasObject' => 0
),
);
$finteredArray = array_filter($arr, function ($r) {
return (bool) $r['hasObject'];
});
print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));

Replace array key integers with string

$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

Problem inserting string into array

i'm trying to insert an implode generated string to an array that then later be used for json implementation
the implode generated string is look like this
'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]
i would like to used it in this code
$this->_JsonArr[]=array($Generated string);
to achieve something like this
$this->_JsonArr[]=array('id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]);
instead i got something like this
$this->_JsonArr[]=array(" 'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]");
seem like generated string is treated as one element as key and value pair.
obviously i can get expected output from mysql because of this, can anybody help me with this
Why do you need to implode anything? Just pass the array:
$this->_JsonArr[] = your-non-imploded-array-here;
I think a full solution to what you want to do is something like this (i.e., the third code box in your question):
$row = array(
'id' => $this->_SqlResult[0],
'UserId' => $this->_SqlResult[1],
'Msg' => $this->_SqlResult[2],
'MsgStamp' => $this->_SqlResult[3]
);
$this->_JsonArr[] = $row;
$this->_JsonArr[]=array($Generated
string);
Looks like you want use arrays keys and values, but as I see you put into array plain string with expectation that array parse your plain string in format: keys => values.
You can try create array like below:
$this->_JsonArr[ $Generated_key ] = array( $Generated_value );
(Please correct me if I wrong understand your question).

array_push() with key value pair

I have an existing array to which I want to add a value.
I'm trying to achieve that using array_push() to no avail.
Below is my code:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?
So what about having:
$data['cat']='wagon';
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey]
=> newValue )
Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need.
No need to use array_push() function for this.
Some time the problem is very simple and we think in complex way :) .
<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
Result
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)
Just do that:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()

Categories