How to limit string length in a multidimensional array? - php

I have a 2-dimensional PHP array containing strings ($fulltable) which I'm trying to fit into the datables grid (https://www.datatables.net/).
Sometimes some of the strings are really long. I'd like to truncate each string to lets say to 75 charachters, which will make the fields more manageable on display.
Is there an easy PHP function to do this or should I just create a double loop like this?
foreach ($fulltable as $row) {
foreach ($row as $field) {
// TRUNCATE FIELD HERE
}
}

You could use array_walk_recursive() to do this and take the value by reference, e.g.
array_walk_recursive($arr, function(&$v){
$v = substr($v, 0, 75);
});

Use mb_substr:
mb_substr($field, 0, 30);
Where 0 is the beginning and 30 is the end, 30 could be anything you want, the length of your output.

array_map() or array_walk() will apply a function to the contents of an array (single dimension), and be probably faster that looping with foreach.
There is also array_walk_recursive() for multi dimensional arrays.

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

Create a set of keys for an array

So I make an API call. This generates an array with dynamic number of elements. I want to add additional empty keys until the number of elements reach 50 (api call will always be lesser than 50). What is the easiest way to do this? Currently I am doing:
$dataArray = $this->APICall();
$toAdd = 50 - count($dataArray);
for($x=$toAdd;$x<=50;$x++)
{
$dataArray[$x] = "";
}
I wanted to check if there is an easier, perhaps single-line way of doing this...
There is function array_fill that you can use to fill array with spaces to size of 50. And then merge it with initial array.
Documentation for array_fill is here
$dataArray = array_merge($dataArray, array_fill(count($dataArray), 50 - count($dataArray), ""));

PHP - How to test a multidimensional array for duplicate element values in any order

I'm not sure the title really gets across what I'm asking, so here's what I'm trying to do:
I have an array of arrays with four integer elements each, ie.
Array(Array(1,2,3,4), Array(4,2,3,1), Array(18,3,22,9), Array(23, 12, 33, 55))
I basically need to remove one of the two arrays that have the same values in any order, like indices 0 and 1 in the example above.
I can do this pretty easily when there are only two elements to check, using the best answer code in this question.
My multidimensional array can have 1-10 arrays at any given time, so I can't seem to figure out the best way to process a structure like that and remove arrays that have the same numbers in any order.
Thanks so much!
I've been thinking about this, and I think using a well designed closure with array_filter might be the way I'd go about this:
$matches = array();
$array = array_filter($array, function($ar) use (&$matches) {
sort($ar);
if(in_array($ar, $matches)) {
return false;
}
$matches[] = $ar;
return true;
});
See here for an example: http://ideone.com/Zl7tlR
Edit: $array will be your final result, ignore $matches as it's just used during the filter closure.

change starting index when assigning one array to another in php

I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.

Deleting all array values from a specific offset and on

I have an array that has 120~ or so offsets and I was wondering how you would delete all the values of said array after a certain offset containing a specified string. For example: Offset [68] has the string 'Overflow'. I want to remove everything including 68 and beyond and rebuild the array (with its current sorting in tact).
I tried messing around with slice and splice but I can't seem to get it to return the right values. I was also thinking of just grabbing the offset number that contains 'Overflow' and then looping it through a for statement until $i = count($array); but that seems a little more intensive than it should be.
Would this be the best way? Or is there some function to do this that I'm just using wrong?
Use array_slice().
$desired = array_slice($input, 0, $upTo);
First you need to find the string occurrence in the array, and, if the value was found, trim the array from that point;
function removeString($string, $array)
{
# search for '$string' in the array
$found = array_search($string, $array);
if ($found === false) return $array; # found nothing
# return sliced array
return array_slice($array, $found);
}
And if you need to make the array sequential (to avoid surprises due to missing offsets), you can always add in the first line $array = array_values($array). This will reorganize the array values in a new array with ordered offsets: 0, 1, 2, 3, 4...

Categories