An array
Array
(
[0] => Array
(
[Detail] => Array
(
[detail_id] => 1
)
)
[1] => Array
(
[Detail] => Array
(
[detail_id] => 4
)
)
)
Is it possible to use implode function with above array, because I want to implode detail_id to get 1,4.
I know it is possible by foreach and appending the array values,
but want to know whether this is done by implode function or any other inbuilt function in PHP
What about something like the following, using join():
echo join(',', array_map(function ($i) { return $i['Detail']['detail_id']; }, $array));
If you need to use some logic - then array_reduce is what you need
$result = array_reduce($arr, function($a, $b) {
$result = $b['Detail']['detail_id'];
if (!is_null($a)) {
$result = $a . ',' . $result;
}
return $result;
});
PS: for php <= 5.3 you need to create a separate callback function for that
Please check this answer.
$b = array_map(function($item) { return $item['Detail']['detail_id']; }, $test);
echo implode(",",$b);
<?php
$array = array(
array('Detail' => array('detail_id' => 1)),
array('Detail' => array('detail_id' => 4)),);
$newarray = array();
foreach($array as $items) {
foreach($items as $details) {
$newarray[] = $details['detail_id'];
}
}
echo implode(', ', $newarray);
?>
Related
What is the easiest way to search in such an array? E.g. search for 5f8ff7a0c49db9d and return 5f8ff7bee02fd05
This doesn't work:
array_search('5f8ff7a0c49db9d', array_column($arr, 1))
[0] : Array
(
[0] => Array
(
[5f8ff7bedde211e] => 5f8e6a74c1d4efe
)
[1] => Array
(
[5f8ff7bee02fd05] => 5f8ff7a0c49db9d
)
[2] => Array
(
[5f8ff7bee2735ce] => 5f8ff7a0c6e8039
)
)
You can reduce the whole array as following:
$keyedByValue = array_reduce($arr, static function(array $carry, array $item) {
return array_merge($carry, array_reverse($item));
}, []);
$yourKey = $keyedByValue['5f8ff7a0c49db9d'];
Or you can even use a simple loop:
$result = null;
$search = '5f8ff7a0c49db9d';
foreach ($arr as $item) {
$item = array_reverse($item);
if (isset($item[$search])) {
$result = $item[$search];
break;
}
}
array_search has this in the examples:
$foundKey = array_search($needle, array_column($array, 'key'));
which works fine
Array
(
[0] => Array
(
[0] => Array
(
[billing_id] => 1
)
[1] => Array
(
[billing_id] => 2
)
)
)
how to display only billing_id from this array?
You can use foreach in billing_id array container :
$my_array = array(0=>array(array('billing_id'=>86),array('billing_id'=>1)));
$i=0;
foreach($my_array as $billingid){
echo $billingid[$i]['billing_id'];
$i++;}
Ex. $data[1]['billing_id']; try like that.
echo $array_name[1]['biling_id']
I don't know how u make it like this but if you need only data : first[0][0]['billing_id']
foreach($x as $m)
{
for($j=0 ; $j<25;$j++){
echo ($m[$i]['billing_id'].",");
}
$i++;
}
where $x is the nameof the array
Try this code:
$result = array_map(function ($element) {
return $element['billing_id'];
}, $arrayName[0]);
echo implode(', ', $result);
shorten code (without commas in result):
array_map(function ($elem) {
echo $elem['billing_id'];
}, $arrayName[0]);
I want difference of multidimensional array with single array. I dont know whether it is possible or not. But my purpose is find diference.
My first array contain username and mobile number
array1
(
array(lokesh,9687060900),
array(mehul,9714959456),
array(atish,9913400714),
array(naitik,8735081680)
)
array2(naitik,atish)
then I want as result
result( array(lokesh,9687060900), array(mehul,9714959456) )
I know the function array_diff($a1,$a2); but this not solve my problem. Please refer me help me to find solution.
Try this-
$array1 = array(array('lokesh',9687060900),
array('mehul',9714959456),
array('atish',9913400714),
array('naitik',8735081680));
$array2 = ['naitik','atish'];
$result = [];
foreach($array1 as $val2){
if(!in_array($val2[0], $array2)){
$result[] = $val2;
}
}
echo '<pre>';
print_r($result);
Hope this will help you.
You can use array_filter or a simple foreach loop:
$arr = [ ['lokesh', 9687060900],
['mehul', 9714959456],
['atish', 9913400714],
['naitik', 8735081680] ];
$rem = ['lokesh', 'naitik'];
$result = array_filter($arr, function ($i) use ($rem) {
return !in_array($i[0], $rem); });
print_r ($result);
The solution using array_filter and in_array functions:
$array1 = [
array('lokesh', 9687060900), array('mehul', 9714959456),
array('atish', 9913400714), array('naitik', 8735081680)
];
$array2 = ['naitik', 'atish'];
$result = array_filter($array1, function($item) use($array2){
return !in_array($item[0], $array2);
});
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => lokesh
[1] => 9687060900
)
[1] => Array
(
[0] => mehul
[1] => 9714959456
)
)
The same can be achieved by using a regular foreach loop:
$result = [];
foreach ($array1 as $item) {
if (!in_array($item[0], $array2)) $result[] = $item;
}
I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}
Basically my app is interacting with a web service that sends back a weird multidimensional array such as:
Array
(
[0] => Array
(
[Price] => 1
)
[1] => Array
(
[Size] => 7
)
[2] => Array
(
[Type] => 2
)
)
That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.
How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?
Appreciate your help
$result = call_user_func_array('array_merge', $array);
Like this:
$result = array();
foreach($array as $inner) {
$result[key($inner)] = current($inner);
}
The $result array would now look like this:
Array
(
[Price] => 1
[Size] => 7
[Type] => 2
)
I am using laravel's helper: http://laravel.com/api/source-function-array_flatten.html#179-192
function array_flatten($array)
{
$return = array();
array_walk_recursive($array, function($x) use (&$return) { $return[] = $x; });
return $return;
}
function flattenArray($input, $maxdepth = NULL, $depth = 0)
{
if(!is_array($input)){
return $input;
}
$depth++;
$array = array();
foreach($input as $key=>$value){
if(($depth <= $maxdepth or is_null($maxdepth)) && is_array($value)){
$array = array_merge($array, flattenArray($value, $maxdepth, $depth));
} else {
array_push($array, $value);
// or $array[$key] = $value;
}
}
return $array;
}
Consider $mArray as multidimensional array and $sArray as single dimensional array this code will ignore the parent array
function flatten_array($mArray) {
$sArray = array();
foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,flatten_array($row));
}
}
return $sArray;
}
I think i found best solution to this : array_walk_recursive($yourOLDmultidimarray, function ($item, $key) {
//echo "$key holds $item\n";
$yourNEWarray[]=$item;
});
If you use php >= 5.6, you may use array unpacking (it's much faster):
$result = array_merge(...$array);
See wiki.php.net on unpacking