Separate array into comma separate strings - php

I want to separate my array into separate strings that all end with a comma.
Array ( [0] => 233d3f9b-3e8e-4e16-ade2-6c165a0324c6
[2] => a6c736b0-f3d2-4907-9d36-6b31adeec2d1
[3] => 1e693cba-d0ce-4a24-bd75-b834e3f44272
)
The purpose of this is so i can pass it to an API. Like this
'optionUuids' => array(
$options2,
),
The option UUidds can contain multiple values as long its separated by a comma in the end.
I tried solving my problem using implode. Implode adds a comma at the end of each line, but it treats this comma as a string. I want to have multiple option UUids so i would need commas that are actually commas and not strings.
Im having trouble explaining this. This is what i expect:
'optionUuids' => array(
233d3f9b-3e8e-4e16-ade2-6c165a0324c6,
a6c736b0-f3d2-4907-9d36-6b31adeec2d1,
1e693cba-d0ce-4a24-bd75-b834e3f44272,
),

You should use
'optionUuids' => array_values(
$options2
),
This will give you all the values but with indices starting from zero

I think, what you want to achieve is not possible
You want to change something like this
["A","B","C"]
into something like this
"A","B","C"
With JS you could do things like this
// JavaScript
arr = [1,2,3]
opt = Array(...arr)
console.log(opt)
But this has no meaning in PHP (in fact it has a meaning, but this would not help you here.) What you would need is a sort of a spread operator like in JavaScript
Unfortunately the spread operator in PHP doesn't work this way. It knows the ... operator, but this is only used in function parameter declarations and function calls. #See https://secure.php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Related

Is there a possible way to use multidimensional arrays to replace words in a string using str_replace() and the array() function?

Note: I have seen this question here, but my array is completely different.
Hello everyone. I have been trying to make a censoring program for my website. What I ended up with was:
$wordsList = [
array("frog","sock"),
array("Nock","crock"),
];
$message = str_replace($wordsList[0], $wordsList[1], "frog frog Nock Nock");
echo $message;
What I am trying to do is replace "frog" with "sock" using multidimentional arrays without typing all of the words out in str_replace();
Expected Output: "sock sock crocs crocs"
However, when I execute it, for some unknown reason it doesn't actually replace the words, without any errors. I think it's a rookie mistake that I made, but I have searched and have not found any documentation on using a system like this. Please help!
You need to change the structure of your wordsList array.
There are two structures that will make it easy:
As key/value pairs
This would be my recommendation since it's super clear what the strings and their replacements are.
// Store them as key/value pairs with the search and replacement strings
$wordsList = [
'frog' => 'sock',
'Nock' => 'crock',
];
$message = str_replace(
array_keys($wordsList), // Get all keys as the search array
$wordsList, // The replacements
"frog frog Nock Nock"
);
Demo: https://3v4l.org/WsUdn
As a multidimensional array
This one requires you to add the search/replacement values in the same order, which can be hard to read when you have a few different strings.
$wordsList = [
['frog', 'Nock'], // All search strings
['sock', 'crock'], // All replacements
];
$message = str_replace(
$wordsList[0], // All search strings
$wordsList[1], // The replacements strings
"frog frog Nock Nock"
);
Demo: https://3v4l.org/RQjC6
If you can't change the original array, then create a new array with the correct structure since that won't work "as is".

Loop through nested arrays in PHP

I have a very complex array that I need to loop through.
Array(
[1] => Array(
[1] => ""
[2] => Array(
[1] => ""
[2] => Array(
[1] => ""
)
)
)
)
I can't use nested loops because this array could contain hundreds of nested arrays. Also, the nested ones could contain nested arrays too.
This array presents comments and replies, Where replies could contain more replies.
Any thoughts?
You could use a \RecursiveArrayIterator, which is part of the PHP SPL, shipped non-optional, with the PHP core.
<?php
$arr = [
'lvl1-A' => [
'lvl2' => [
'lvl3' => 'done'
],
],
'lvl1-B' => 'done',
];
function traverse( \Traversable $it ): void {
while ( $it->valid() ) {
$it->hasChildren()
? print "{$it->key()} => \n" and traverse( $it->getChildren() )
: print "{$it->key()} => {$it->current()}\n";
$it->next();
}
}
$it = new \RecursiveArrayIterator( $arr );
$it->rewind();
traverse( $it );
print 'Done.';
Run and play this example in the REPL here: https://3v4l.org/cGtoi
The code is just meant to verbosely explain what you can expect to see. The Iterator walks each level. How you actually code it is up to you. Keep in mind that filtering or flattening the array (read: transforming it up front) might be another option. You could as well use a generator and emit each level and maybe go with Cooperative Multitasking/ Coroutines as PHP core maintainer nikic explained in his blog post.
ProTip: Monitor your RAM consumption with different variants in case your nested Array really is large and maybe requested often or should deliver results fast.
In case you really need to be fast, consider streaming the result, so you can process the output while you are still working on processing the input array.
A last option might be to split the actual array in chunks (like when you are streaming them), therefore processing smaller parts.
The case is quite complex, as you have to loop, but you can't or don't want to for some reasons:
... that I need to loop through
and
I can't use nested loops because this array could contain hundreds of nested arrays
It means you have to either handle your data differently, as you can pack that huge amount of data to be processed later.
If for some reasons it's not an option, you can consider to:
split somehow this big array into smaller arrays
check how does it work with json_encode and parsing string with str_* functions and regex
Your question contains too many things we can't be sure e.g. what exactly these subarrays contain, can you ignore some parts of them, can you change the code that creates huge array in first place etc.
Assuming on the other hand that you could loop. What could bother you? The memory usage, how long it will take etc.?
You can always use cron to run it daily etc. but the most important is to find the cause why you ended up with huge array in the first place.

How to split a search url into an associative array

So I would like to take a string like this,
q=Sugar Beet&qf=vegetables&range=time:[34-40]
and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.
I want it to look like this
['q'] => ['Sugar Beets],
['qf'] => ['vegetables']
After using urlencode I get
q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D
Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.
After this, the plan was to take the two array and combine them with array_combine().
So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.
PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.
You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():
$str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
parse_str($str, $params);
print_r($params);
Produces the output:
Array
(
[q] => Sugar Beet
[qf] => vegetables
[range] => time:[34-40]
)
You could use the parse_url() function/.
also:
parse_str($_SERVER['QUERY_STRING'], $params);

Combining 2 Arrays So That They Display Correctly in my URL

I have an array $cat1 including
cat1[0]=>16 and cat1[1]=>16.
I also have this array:
$url_vars = array('text'=>$event->properties['text'],'SearchResultPagerPage'=>$thenextpage);
I need to put these combined into this URL function:
$this->URL('SearchResult','',$url_vars);
So that the resulting URL needs to look like this:
/SearchResult.html?text=cat&SearchResultPagerPage=1&cat1[]=1&cat1[]=16
Currently, if I combine them, I get this as the resulting combined array:
Array
(
[text] => cat
[SearchResultPagerPage] => 1
[0] => 1
[1] => 16
)
and this as the resulting URL:
SearchResult.html?&text=cat&SearchResultPagerPage=1&1=16
How do I form this so that it says cat1[]=1&cat1[]=16 instead of 1=16?
Thanks very much for any help anyone might offer!!
If you MUST use the URL function $this->URL('SearchResult','',$url_vars); then one idea is to use indices in the cat1 array. That is:
$url_vars["cat1[0]"] = 1;
$url_vars["cat1[1]"] = 16;
This will result in your query string having
...&cat1[0]=1&cat1[1]=16
with the []'s probably escaped, but perhaps your server script can properly accommodate these indices. It is worth a try. Otherwise you'll have to generate the URL outside of the URL function, because you can't have a php array with identical keys "cat1[]" but two separate values.
EDIT: One other thing to try in case your URL function is intelligent enough:
$url_vars["cat1"] = [1,16];

Convert list (array) to associative array in PHP

I want to convert PHP list (array), i.e.
array("start", "end", "coords")
into associative array with truthy values (just to be able to test the presence/absence of key quickly), i.e. to something like this:
array(
"start" => 1,
"end" => 1,
"coords" => 1
)
Is there any more elegant way to do it than this?
array_fill_keys($ar, 1)
There is probably no more elegant solution than array_fill_keys($ar, 1).
There is a function called array_flip that does this.
http://php.net/array_flip
Doing array_flip on an array and then using isset turned out to be much faster than doing in_array for me.
But note that this is only useful when you're going to be searching the array multiple times.

Categories