php turn this array into integer series - php

this is the output of my array
[["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]]
but I would like this to look like
[1,1,1,1,1,1,1]
how would this be achieved in php, it seems everything I do gets put into an object in the array, when I don't want that. I tried using array_values and it succeeded in returning the values only, since I did have keys originally, but this is still not the completely desired outcome

$yourArray = [["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]];
use following code in PHP 5.3+
$newArray = array_map(function($v) {
return (int)$v[0];
}, $yourArray);
OR use following code in other PHP version
function covertArray($v) {
return (int)$v[0];
}
$newArray = array_map('covertArray', $yourArray)

You could always do a simple loop...
$newArray = array();
// Assuming $myArray contains your multidimensional array
foreach($myArray as $value)
{
$newArray[] = $value[0];
}
You could beef it up a little and avoid bad indexes by doing:
if( isset($value[0]) ) {
$newArray[] = $value[0];
}
Or just use one of the many array functions to get the value such as array_pop(), array_slice(), end(), etc.

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;
}

How to combine array values and separate constants without using foreach construction?

I'm trying to find a simpler way to create new arrays from existing arrays and values. There are two routines I'd like to optimize that are similar in construction. The form of the first one is:
$i = 0;
$new_array = array();
foreach ($my_array as $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$i++;
}
The form of the second one has not one but two different values per constant; notice that $value comes before $key in the indexing:
$i = 0;
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$new_array[$i][2] = $key; // different for each index of $my_array
$i++;
}
Is there a way to optimize these procedures with shorter and more efficient routines using the array operators of PHP? (There are many, of course, and I can't find one that seems to fit the bill.)
I believe a combination of Wouter Thielen's suggestions regarding the other solutions actually holds the best answer for me.
For the first case I provided:
$new_array = array();
// $my_array is numeric, so $key will be index count:
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value);
};
For the second case I provided:
// $my_array is associative, so $key will initially be a text index (or similar):
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value, $key);
};
// This converts the indexes to consecutive integers starting with 0:
$new_array = array_values($new_array);
it is shorter, when you use the array-key instead of the $i-counter
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key][0] = $constant; // defined previously and unchanging
$new_array[$key][1] = $value; // different for each index of $my_array
}
Use array_map:
$new_array = array_map(function($v) use ($constant) {
return array($constant, $v);
}, $my_array);
If you want to use the keys too, for your second case:
$new_array = array_map(function($k, $v) use ($constant) {
return array($constant, $v, $k);
}, array_keys($my_array), $my_array);
Assuming the $constant variable is defined in the caller's scope, you'll need to use use ($constant) to pass it into the function's scope.
array_walk is similar, but modifies the array you pass to it, so if you want to update $my_array itself, use array_walk. Your second case then becomes this:
array_walk($my_array, function(&$val, $key) use($constant) {
$val = array($constant, $val, $key);
});
In both examples above for the second case, you'll end up with an associative array (i.e. with the keys still being the keys for the array). If you want to convert this into a numerically indexed array, use array_values:
$numerically_indexed = array_values($associative);
I asked a question similar to this a few days ago, check it out:
PHP - Fastest way to convert a 2d array into a 3d array that is grouped by a specific value
I think that you have an optimal way when it comes to dealing with large amount of data. For smaller amounts there is a better way as was suggested by the benchmarks in my question.
I think too that readability and understanding the code can also be an issue here and I find that things that you can understand are worth more later on than ideas that you do not really grasp as it generally takes a long time to understand them again as it can be quite confusing while debugging issues.
I would suggest, you take a look at the differences between JSON encoded arrays and serialised arrays as there can be major performance differences when working with the two. It seems that as it is now JSON encoded arrays are a more optimised format (faster) for holding and working with data however this will likely change with PHP 7. It would be useful to note that they are also more portable.
Further Reading:
Preferred method to store PHP arrays (json_encode vs serialize)
http://techblog.procurios.nl/k/n618/news/view/34972/14863/cache-a-large-array-json-serialize-or-var_export.html

Array of values from and array of arrays without loops

Let's say I have a data set in PHP that is in the form of:
$array = [{"prior":"0","id":"61039","type":"todo"},
{"prior":"1","id":"70341","type":"todo"},
{"prior":"3","id":"39104","type":"todo"},
{"prior":"4","id":"70315","type":"todo"},
{"prior":"6","id":"72050","type":"todo"},
{"prior":"7","id":"72329","type":"todo"},
{"prior":"8","id":"73992","type":"todo"}]
I want to process this array of arrays so that I have a single array with integer indexes and the values of only id.
It's trivial to simple use loops:
$data = array();
foreach($array as $item){
$data[] = $item['id'];
}
What I want to know, is there a way to do this, disregarding efficiency, using the built in array functions of PHP (with no loops), or am I stuck using the foreach loop?
You can use array_map() for this:
$data = array_map(function ($el) { return $el['id']; }, $array);
Note that this still has to perform the looping internally; it's just not shown explicitly as in a foreach loop. This approach will be far less efficient than a plain 'ol foreach.
Demo
With PHP >= 5.5.0:
$array = json_decode($array, true);
$ids = array_column($array, 'id');

Storing array data in foreach loop in PHP

I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:
$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
$arr = array('val' => $row);
echo $row;
}
print_r($arr);
So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.
My question would be how can I store each instance of row in my array?
Create a new array, fill it:
$array = array("v1", "v2", "v3", "v4");
$newArray = array();
foreach($array as $row){
// notice the brackets
$newArray[] = array('val' => $row);
}
print_r($newArray);
It looks like you are storing your array wrong.
Try adjusting the $arr = array('val' => $row);
to:
$arr[] = array('val' => $row);
This will set it so you pick up each line as a separate array which you can easily navigate through.
Hope this helps!
If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.
$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);
While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.
Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.

how to search an array in php?

suppose I have an array of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array. Is this possible ? if yes then please can your give me hint ? I am new to programming.
To offer yet another solution, I would recommend using PHP's internal array_filter to perform the search.
function applyFilter($element){
// test the element and see if it's a match to
// what you're looking for
}
$matches = array_filter($myArray,'applyFilter');
As of PHP 5.3, you can use an anonymous function (same code as above, just declared differently):
$matches = array_filter($myArray, function($element) {
// test the element and see if it's a match to
// what you're looking for
});
what you would need to di is map the array with a callback like so:
array_filter($myarray,"CheckMatches");
function CheckMatches($key,$val)
{
if(preg_match("...",$val,$match))
{
return $match[2];
}
}
This will run the callback for every element in the array!
Updated to array_filter
well in this case you would probably do something along the lines of a foreach loop to iterate through the array to find what you are looking for.
foreach ($array as $value) {
if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}
If you wish to use a PHP built in method, you can use in_array
$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';
1) Store the strings in array1
2) array2 against you want to match
3) array3 in which you store the matches
$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
if(in_array($value,$array2))
$array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';

Categories