combine two arrays in php in unique case [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have the following 2 arrays variable.
$a = array("triple","triple","double","single","single");
$b = array("444","555","33","2","3");
i need to convert that 2 arrays to be this array pattern
$array = array(
"triple"=>array("444","555"),
"double"=>array("33"),
"single"=>array("2","3")
);
so that i can get the result like this
triple(444 | 555) double(33) single(2 | 3)
anyone can help me? thanks

Just use array_combine, $b as keys and $a as values, then transfer to a new container grouping them with the key:
$array = array();
foreach(array_combine($b, $a) as $k => $v) {
$array[$v][] = $k;
}
For presentation purposes, just implode them:
foreach($array as $key => $numbers) {
$href = implode('|', $numbers);
$numbers = $key . '(' . implode(' | ', $numbers) . ')' . ' ';
echo "<a href='aaa.php?numbers=$href'>$numbers</a>";
}

You Can use PHP's Array_unique ... Follow this link
And do the following..
$arr = [];
foreach($a as $value) {
if ( $value == 'tripple' ) {
foreach( $b as $val ) if( strlen($val) == 3 ) $arr[$value][] = $val;
}
if ( $value == 'double' ) {
foreach( $b as $val ) if( strlen($val) == 2 ) $arr[$value][] = $val;
}
if ( $value == 'single' ) {
foreach( $b as $val ) if( strlen($val) == 1 ) $arr[$value][] = $val;
}
}
That should work...

Related

Convert dictionary to string (PHP) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 15 hours ago.
Improve this question
I need to write a function that converts a dictionary (array) ['a' => 1, 'b' => 2] to a string '[a => 1, b => 2]'.
I am trying to iterate over the array and just build a string from its items:
function dictToString(array $dict): string {
foreach($dict as $key => $value) {
echo $key . " => " . $value . ", ";
}
return "";
}
However, I'm not sure how to perform it well. I am getting such output: a => 1, b => 2,. Don't know how to include brackets and get rid of the redundant comma.
Also not sure if this is even a good approach, maybe there's a better way.
You can use something like this
function dictToString(array $dict): string {
$str = '[';
foreach($dict as $key => $value) {
$str .= $key . " => " . $value . ", ";
}
$str = rtrim($str, ", ");
$str .= ']';
return $str;
}
echo dictToString(['a' => 1, 'b' => 2]);
rtrim() remove the comma from the last iteration
There are different ways to do it. I'd use array_map() and implode() methods to avoid looping each element
function dictToString($dict) {
$pairs = array_map(function($key, $value) {
return $key . ' => ' . $value;
}, array_keys($dict), $dict);
return '[' . implode(', ', $pairs) . ']';
}
Maybe will be better use function json_encode

PHP Search for arrays and extract comma [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have one array
Array (
[1]=>123,456,789,3255
[2]=>585,478,437,1237
)
Search Text = 12
output I want -> 123,1237
What way should I go?
$array = array();
array_push($array,'1234',534,75,746);
array_push($array,'164',574,752,755);
array_push($array,'154',58,754,76);
$search_text = '75';
I want Output =
75,752,755,754
You can do this using strpos and a loop.
$numbers = array();
array_push($numbers,'1234', 534, 75, 746);
array_push($numbers,'164', 574, 752, 755);
array_push($numbers,'154', 58, 754, 76);
$searchNumber = '75';
$output = [];
foreach ($numbers as $number) {
if (strpos((string) $number, $searchNumber) !== false) {
$output[] = $number;
}
}
// 75, 752, 755, 754
echo implode(", ", $output);
If you are using PHP 8 you could even replace the strpos with str_contains function
if (str_contains($number, $searchNumber)) {
$output[] = $number;
}
RFC
str_contains
Try this:
$result = [];
$array = [];
$toSearch = '75';
array_push($array,'1234',534,75,746);
array_push($array,'164',574,752,755);
array_push($array,'154',58,754,76);
// If your array is one dimension
$result = array_filter($array, function($el) use ($toSearch) {
return strpos((string) $el, (string) $toSearch);
});
// For 2D array:
foreach ($array as $cur) {
$result = array_merge($result, array_filter($cur, function($el) use ($toSearch) {
return strpos((string) $el, (string) $toSearch);
}));
}

PHP how to delete deep keys programmatically

Imagine you have a deep array like this:
<?php
$array = ['hello' => ['deep' => 'treasure']];
Then you had an array of the keys to access the string 'treasure'
['hello', 'deep'];
How do you delete the string treasure if you did not know the depth of the array till run time
Edit:
My apologises I've definitely not provided enough information for what I'm looking to achieve
Here is some code I've come up with which does what I need but uses unsafe eval (keep in mind the target destination could be an array so array_walk_recursive won't work)
function iterator_keys($iterator, $outer_data) {
$keys = array();
for ($i = 0; $i < $iterator->getDepth() + 1; $i++) {
$sub_iterator = $iterator->getSubIterator($i);
$keys[$i] = ($i == 0 && is_object($outer_data)
|| $i > 0 && is_object($last_iterator->current())) ?
'->{"' . $sub_iterator->key() . '"}' :
'["' . $sub_iterator->key() . '"]';
$last_iterator = $sub_iterator;
}
return $keys;
}
function recursive_filter($data, callable $selector_function, $iterator = NULL) {
$iterator = $iterator ?? new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $key => $value) {
if ($selector_function($value, $key, $iterator)) {
eval('unset($data' . implode('', iterator_keys($iterator, $data)) . ');');
}
}
return $data;
}
The intention is to have a deep data structure a function that evalutes each node and if it matches a condition then remove it from the data structure in place, if this can be done without eval that would be amazing but so far I think PHP can't programmatically delete something that is more than one level deep
Hello I think what you want is somethings like this
<?php
$array = ['hello' => ['deep' => ['deep1' => 'treasure']]];
$keys = ["hello", "deep", "deep1"];
function remove_recursive(&$array, $keys, $level = 0)
{
if ($level >= count($keys)) {
return $array;
}
if (isset($array[$keys[$level]]) && $level == count($keys) - 1) {
unset($array[$keys[$level]]);
} elseif (isset($array[$keys[$level]])) {
$array[$keys[$level]] = remove_recursive($array[$keys[$level]], $keys, $level + 1);
}
return $array;
}
var_dump(remove_recursive($array, $keys));
Well you can try this really quick and dirty way that uses eval to achieve your goal:
$array = ['hello' => ['deep' => 'treasure']];
$keys = ['hello', 'deep'];
$expression = 'unset($array[\'' . implode('\'][\'', $keys) . '\']);';
eval($expression);
But maybe you can tell us more about your development and we can help you reorganize it somehow to avoid this problem at all.
This will set the target array element to null. Optionally you could use '':
$array = ['hello' => ['deep' => 'treasure']];
$path = ['hello', 'deep'];
$temp = &$array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = null;
print_r($array);
Yields:
Array
(
[hello] => Array
(
[deep] =>
)
)

Strip all elements from array where they occur less than twice

I have an array like this:
[0] = 2
[1] = 8
[2] = 7
[3] = 7
And I want to end up with an array that looks like:
[0] = 7
[1] = 7
Basically, remove all elements where they occur less than twice.
Is their a PHP function that can do this?
try this,
$ar1=array(2,3,4,7,7);
$ar2=array();
foreach (array_count_values($ar1) as $k => $v) {
if ($v > 1) {
for($i=0;$i<$v;$i++)
{
$ar2[] = $k;
}
}
}
print_r($ar2);
output
Array ( [0] => 7 [1] => 7 )
Something like this would work, although you could probably improve it with array_reduce and an anonymous function
<?php
$originalArray = array(2, 8, 7, 7);
foreach (array_count_values($originalArray) as $k => $v) {
if ($v < 2) {
$originalKey = array_search($k, $originalArray);
unset($originalArray[$originalKey]);
}
}
var_dump(array_values($originalArray));
$testData = array(2,8,7,7,5,6,6,6,9,1);
$newArray = array();
array_walk(
array_filter(
array_count_values($testData),
function ($value) {
return ($value > 1);
}
),
function($counter, $key) use (&$newArray) {
$newArray = array_merge($newArray,array_fill(0,$counter,$key));
}
);
var_dump($newArray);
Though it'll give a strict standards warning. To avoid that, you'd need an interim stage:
$testData = array(2,8,7,7,5,6,6,6,9,1);
$newArray = array();
$interim = array_filter(
array_count_values($testData),
function ($value) {
return ($value > 1);
}
);
array_walk(
$interim,
function($counter, $key) use (&$newArray) {
$newArray = array_merge($newArray,array_fill(0,$counter,$key));
}
);
var_dump($newArray);
You could use a combination of array_count_values (which will give you an associative array with the value as the key, and the times it occurs as the value), followed by a simple loop, as follows:
$frequency = array_count_values($yourArray);
foreach ($yourArray as $k => $v) {
if (!empty($frequency[$v]) && $frequency[$v] < 2) {
unset($yourArray[$k]);
}
}
I did not test it, but I reckon it works out of the box. Please note that you will loop over your results twice and not N^2 times, unlike an array_search method. This can be further improved, and this is left as an exercise for the reader.
This was actually harder to do than i thought...anyway...
$input = array(2, 8, 7, 7, 9, 9, 10, 10);
$output = array();
foreach(array_count_values($input) as $key => $value) {
if ($value > 1) $output = array_merge($output, array_fill(0, $value, $key));
}
var_dump($output);
$arrMultipleValues = array('2','3','5','7','7','8','2','9','11','4','2','5','6','1');
function array_not_unique($input)
{
$duplicatesValues = array();
foreach ($input as $k => $v)
{
if($v>1)
{
$arrayIndex=count($duplicatesValues);
array_push($duplicatesValues,array_fill($arrayIndex, $v, $k));
}
}
return $duplicatesValues;
}
$countMultipleValue = array_count_values($arrMultipleValues);
print_r(array_not_unique($countMultipleValue));
Is their [sic!] a PHP function that can do this?
No, PHP has no built-in function (yet) that can do this out of the box.
That means, if you are looking for a function that does this, it needs to be in PHP userland. I would like to quote a comment under your question which already suggest you how you can do that if you are looking for that instead:
array_count_values() followed by a filter with the count >1 followed by an array_fill() might work
By Mark Baker 5 mins ago
If this sounds a bit cryptic to you, those functions he names are actually built-in function in PHP, so I assume this comes most close to the no, but answer:
array_count_values()
array_fill()
This does the job, maybe not the most efficient way. I'm new to PHP myself :)
<?php
$element = array();
$element[0] = 2;
$element[1] = 8;
$element[2] = 7;
$element[3] = 7;
$count = array_count_values($element);
var_dump($element);
var_dump($count);
$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($count));
$result = array();
foreach ($it as $key=>$val){
if ($val >= 2){
for($i = 1; $i <= $val; $i++){
array_push($result,$key);
}
}
}
var_dump($result);
?>
EDIT: var_dump is just so you can see what's going on at each stage

PHP Turn a Numbered String List into Array

With PHP if you have a string which may or may not have spaces after the dot, such as:
"1. one 2.too 3. free 4. for 5.five "
What function can you use to create an array as follows:
array(1 => "one", 2 => "too", 3 => "free", 4 => "for", 5 => "five")
with the key being the list item number (e.g the array above has no 0)
I presume a regular expression is needed and perhaps use of preg_split or similar? I'm terrible at regular expressions so any help would be greatly appreciated.
What about:
$str = "1. one 2.too 3. free 4. for 5.five ";
$arr = preg_split('/\d+\./', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
I got a quick hack and it seems to be working fine for me
$string = "1. one 2.too 3. free 4. for 5.five ";
$text_only = preg_replace("/[^A-Z,a-z]/",".",$string);
$num_only = preg_replace("/[^0-9]/",".",$string);
$explode_nums = explode('.',$num_only);
$explode_text = explode('.',$text_only);
foreach($explode_text as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$text_array[] = $value;
}
}
foreach($explode_nums as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$num_array[] = $value;
}
}
foreach($num_array as $key => $value)
{
$new_array[$value] = $text_array[$key];
}
print_r($new_array);
Test it out and let me know if works fine

Categories