how to make array like this - php

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

Related

PHP- Create an array with the matches of two arrays

I am trying to compare two non-associative arrays to create a new array with the matches.
This is what I have though:
//This array has several entries
$a_firstarray = Array();
//This array has less entries than the first array
$a_secondarray = Array();
//This array should contain the matches of the first array and the second array in no particular order
$a_mergedarray
for($i=0;$i <=count($a_firstarray);$i++){
for($a=0;$a <=count ($a_secondarray);$a++){
if($a_firstarray[$i] == $a_secondarray[$a]){
$a_mergedarray[] = $a_activecategory[$i];
}
}
}
It doesn't work for some reason. I am also sure that PHP has some sort of function that does this. Any ideas? thanks in advance.
This is known as the "intersection" of two arrays. PHP provides array_intersect.
use array_intersect.
$result = array_intersect($array1, $array2);
Are you looking for array_intersect()?
http://php.net/manual/en/function.array-intersect.php

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');

php turn this array into integer series

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.

Extract parts from Array keys in php and combine them

i have also got a similar question. I have an array where i need to extract parts from the keys of array and combine them. can you please suggest the best way for it.
$myarray=Array(
[0]=>'unwanted text'
[1]=>'unwanted+needed part1'
[2]=>'needed part2'
[3]=>'needed part3'
[4]=>'unwanted text'
)
how can i extract only the needed parts and combine them. Thanks a lot ahead.
Not exactly sure if this does what you want, but looping and copying to a new array should basically achieve your result (once you clarify how you decide which part of the strings are needed or unwanted)
$myarray = array(…);
$new_array = array();
$unwanted = 'some_string';
foreach($myarray as $k => $v) {
$new_value = preg_replace("/^$unwanted/", '', $v); # replace unwanted parts with empty string (removes them);
if(!empty($new_value)) { # did we just remove the entry completely? if so, don't append it to the new array
$new_array[] = $v; # or $new_array[$k] if you want to keep indices.
}
}
Assuming you want to join array entries and have a string as result, use the implode function of PHP: $string = implode(' ', $new_array);
The functions you are after, depending on what you want to do, will be a combination of the following: array_splice, array_flip, array_combine.
array_splice()
allows you to extract part of an array by key offset. It'll permanently remove the elements from the source, and return these elements in a new array
array_flip()
Turns keys into values and values into keys. If you have multiple identical values, the last one has precedence.
array_combine() takes two parameters: an array of keys, and an array of values, and returns an associative array.
You'll need to provide more info as to what you want to do, though, for my answer to be more specific.

Type check in all array elements

Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))

Categories