I have an array of array like this
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
I have value 9908. When I search 9908 then the value array("9908","1","5") should be printed. I have used array_search() but I have not got any success
How I can print the array after finding the value
Try this:
var_dump($data[array_search("9908", array_column($data, 0))]);
To expand it,
array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
array_search Searches the array for a given value and returns the first corresponding key if successful.
Edit:
To add some control over it:
$index = array_search("9908", array_column($data, 0));
if($index !== false){
// do your stuff with $data[$index];
var_dump($data[$index]);
}
Dumps:
array(3) {
[0]=>
string(4) "9908"
[1]=>
string(1) "1"
[2]=>
string(1) "5"
}
Perhaps this can help:
<?php
function search_first_row($needle, $haystack){
$data = $haystack;
$desired_value = $needle;
foreach($data as $row){
if($row[0] == $desired_value){
return $row;
}
}
}
try this :
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
foreach ($data as $key => $value) {
if( in_array("9908",$value)){
$findindex = $key;
}
}
var_dump($data[$findindex]);
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
$searchValue = '9908';
for($i=0; $i<count($data); $i++){
$innerArray = $data[$i];
for($j=0; $j<count($innerArray); $j++){
if($innerArray[$j] == $searchValue){
print_r($innerArray);
}
}
}
Related
So I have two arrays:
$gated_categories
array(2) { [0]=> int(3511) [1]=> int(3510) }
and
$category_id
array(3) { [0]=> int(3518) [1]=> int(3511) [2]=> int(3502) }
As you can see above, both arrays contain 3511
So if $gated_categories contains a value which is is $category_id
I want this to return true, else false
I have tried with this:
$is_gated = !array_diff($gated_categories, $category_id);
But this is returning false, any ideas?
array_diff() does the opposite of what you want. It returns an array with the values of the first array that are not present in the other array(s).
You need array_intersect().
if (count(array_intersect($arr1, $arr2))) {
//at least one common value in both arrays
}
You can do the following, loop over the array you want to check it's values and use in_array function.
Something like this:
<?php
function checkCategory(): bool {
$gated_categories = [3510, 3511];
$category_id = [3502, 3511, 3518];
foreach ($gated_categories as $cat) {
if (in_array($cat, $category_id)) {
return true;
}
}
return false;
}
var_dump(checkCategory());
You can solve this problem with use from array_diff two times
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
print_r(findGatedCategoriesContainCategoryId($gated_categories, $category_id));
function findGatedCategoriesContainCategoryId($gated_categories, $category_id) {
$arrayDiff = array_diff($gated_categories, $category_id);
return array_values(array_diff($gated_categories ,$arrayDiff));
}
?>
output
Array
(
[0] => 3511
)
Or just use array_intersect like this
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
$result = array_intersect($gated_categories, $category_id);
print_r($result);
?>
output
Array
(
[0] => 3511
)
I am trying to locale the correct sub-array in order to change the count, if a specific value is present more than once.
I have the following code:
$trending = [];
foreach($hashtags as $hashtag) {
if(in_array($hashtag->hashtag, $hashtags))
{
array_search()
}
else {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
}
This gives me the following example outout:
array(3) {
[0]=> array(2)
{
["hashtag"]=> "foobar"
["counts"]=> "1"
}
[1]=> array(2)
{
["hashtag"]=> "hashtags"
["counts"]=> "1"
}
[2]=> array(2)
{
["hashtag"]=> "imageattached"
["counts"]=> "1"
}
}
So in the foreach loop and the if statement, i want to check for dublicates of hashtags, e.g. if the hashtag foobar exists more than one time, I don't want to create another dublicate in the array, but I want to change the count to 2
How do I find the correct "sub"-array, and change the count of this to 2, if a hashtag is present within $hashtags more than once??
The idea is, that I at the end can sort these arrays, and get the hashtag that is most common, by looking at the count.
If you change the structure of your output, you could do something like this:
$trending = [];
foreach($hashtags as $tag) {
if (isset($trending[$tag])) $trending[$tag]++;
else $trending[$tag] = 1;
}
Which would result in $trending having the structure
array(2) {
["foobar"] => 1,
["hashtags"] => 2
}
Which could then be looped through with
foreach($trending as $tag => $count) {
echo $tag . ' appears ' . $count . ' times.' . PHP_EOL;
}
The PHP method array_count_values might be of some help.
http://php.net/manual/en/function.array-count-values.php
Have you considered using a keyed array?
$trending = array();
foreach($hashtags as $hashtag) {
if(!isset($trending[$hashtag])){
$trending[$hashtag] = 1;
}else{
$trending[$hashtag] += 1;
}
}
By using a keyed array, there is no duplication and you can easily check how frequently a hashtag is used by just accessing $trending[$hashtag]. Additionally, you can get the list of all hashtags in the trending array using $allHashtags = array_keys($trending);.
Of course, if your project specifications do not allow for this, then by all means, use a different approach, but that would be the approach I would take.
It can be more linear of you can change your array structure but for the current this should work.
$trending = [];
$checker = true;
foreach($hashtags as $hashtag) {
foreach ($trending as $key =>$value) {
if($value["hashtag"] == $hashtag->hashtag){
$trending[$key]["counts"]++;
$checker = false;
}
}
if($checker) {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
$checker = true;
}
I tried to use the function array_search but can't get it work..
I got a php session with an array.
array(2) {
[0]=>
array(6) {
["ProductId"]=>string(2) "34"
["ProductName"]=>string(9) "Best ever"
["ProductPrice"]=>string(6) "453.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "d12f95895c9130da8e52a7ff5b9216c9.png"
}
[1]=>
array(6) {
["ProductId"]=>string(2) "33"
["ProductName"]=>string(5) "Vespa"
["ProductPrice"]=>string(7) "1789.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "678e25ea94a7fa94bc6fa427ff29bc6c.png"
}
now I do an array_search()
session_start();
include '_sqlclean.php';
(isset($_POST['product_id'])) ? $p_id = clean_string_save($_POST['product_id']) : $p_id = 0;
$array = $_SESSION['wishList'];
$key = array_search($p_id, $array);
if I do a
var_dump($_SESSION['wishList']);
I got what I showed you above.
But I always got the message "Key not found"
Why ?? What's my mistake ?
I tried already to do
$p_id = "34" // for try
$p_id = intval(34); // for try also
$key = array_search("34", $_SESSION['wishList']); // to see if it works
but nothing worked.. :(
Thanks in advance
array_search will not work for multidimensional arrays. Rather this might work -
$key = array_search($p_id, array_column($array, 'ProductId'));
This will extract all the ProductId from that array then do the search.
Try with alternative for array_search().For example:
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
OR
$key = array_search($p_id, array_column($array, 'ProductId'));
Aparently you are mistyping the variable (key) name
in the array it is
ProductId
and in your code it is
Product_Id
It happen cause you search into outer array, which contains only [0] and [1] keys.
Try to use
$key = array_search("34", $_SESSION['wishList'][1]);
You can try an alternative way like
<?php
$p_id = "34" // for try
$p_id = intval(34); // for try also
if(in_array($p_id, array_values($_SESSION['wishList']))) {
// Product Id found in your wishList
}
?>
It will works only for single dimension array. For multidimensional use foreach loop.
Say, we have an array: array(1,2,3,4,...)
And I want to convert it to:
array(
1=>array(
2=>array(
3=>array(
4=>array()
)
)
)
)
Can anybody help?
Thanks
EDIT It would be good to have the solution with iterations.
$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
$temp = array($array[$i] => $temp);
}
You can simply make a recursive function :
<?php
function nestArray($myArray)
{
if (empty($myArray))
{
return array();
}
$firstValue = array_shift($myArray);
return array($firstValue => nestArray($myArray));
}
?>
Well, try something like this:
$in = array(1,2,3,4); // Array with incoming params
$res = array(); // Array where we will write result
$t = &$res; // Link to first level
foreach ($in as $k) { // Walk through source array
if (empty($t[$k])) { // Check if current level has required key
$t[$k] = array(); // If does not, create empty array there
$t = &$t[$k]; // And link to it now. So each time it is link to deepest level.
}
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();
Output:
array(1) {
[1]=> array(1) {
[2]=> array(1) {
[3]=> array(1) {
[4]=> array(0) {
}
}
}
}
}
I think the syntax for the multidimensional array you want to create would look like the following.
$array = array(
'array1' => array('value' => 'another_value'),
'array2' => array('something', 'something else'),
'array3' => array('value', 'value')
);
Is this what you're looking for?
You can also use this array library to do that in just one line:
$array = Arr::setNestedElement([], '1.2.3.4', 'value');
I have an array in PHP that looks like this:
[0]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url.com/"
}
[1]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url2.com/"
}
The two values in "name" are the same in this two items. I want to sort out duplicates like this.
How do I create an unique array by checking the "name" value?
basically
$unique_array = [];
foreach($your_array as $element) {
$hash = $element[field-that-should-be-unique];
$unique_array[$hash] = $element;
}
$result = array_values($unique_array);
Serialisation is very useful for simplifying the process of establishing the uniqueness of a hierarchical array. Use this one liner to retrieve an array containing only unique elements.
$unique = array_map("unserialize", array_unique(array_map("serialize", $input)));
Please find this link useful, uses md5 hash to examine the duplicates:
http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html
Quick Glimpse:
/**
* Create Unique Arrays using an md5 hash
*
* #param array $array
* #return array
*/
function arrayUnique($array, $preserveKeys = false)
{
// Unique Array for return
$arrayRewrite = array();
// Array with the md5 hashes
$arrayHashes = array();
foreach($array as $key => $item) {
// Serialize the current element and create a md5 hash
$hash = md5(serialize($item));
// If the md5 didn't come up yet, add the element to
// to arrayRewrite, otherwise drop it
if (!isset($arrayHashes[$hash])) {
// Save the current element hash
$arrayHashes[$hash] = $hash;
// Add element to the unique Array
if ($preserveKeys) {
$arrayRewrite[$key] = $item;
} else {
$arrayRewrite[] = $item;
}
}
}
return $arrayRewrite;
}
$uniqueArray = arrayUnique($array);
var_dump($uniqueArray);
See the working example here:
http://codepad.org/9nCJwsvg
Simple Solution:
/**
* #param $array
* #param null $key
* #return array
*/
public static function unique($array,$key = null){
if(null === $key){
return array_unique($array);
}
$keys=[];
$ret = [];
foreach($array as $elem){
$arrayKey = (is_array($elem))?$elem[$key]:$elem->$key;
if(in_array($arrayKey,$keys)){
continue;
}
$ret[] = $elem;
array_push($keys,$arrayKey);
}
return $ret;
}
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$result = unique_multidim_array($visitors,'ip');
Given that the keys on the array (0,1) do not seem to be significant a simple solution would be to use the value of the element referenced by 'name' as the key for the outer array:
["My_item"]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url.com/"
}
...and if there is only one value other than the 'name' why bother with a nested array at all?
["My_item"]=>"http://www.my-url.com/"