Get PHP array value [duplicate] - php

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 9 years ago.
I have an array like the following:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 3
)
[2] => Array
(
[0] => 4
)
)
Now I want each array value into one single array. How do I do it?
Thanks in advance.

// PHP >= 5.3:
function array_value_recursive($key, array $arr){
$val = array();
array_walk_recursive($arr, function($v, $k) use($key, &$val){
if($k == $key) array_push($val, $v);
});
return $val;
}

You can recursively parse the array with a function:
$multiDimArr = array(...);
function getSingleArray( $multiDimArr ) {
$singleArray = array();
foreach($multiDimArr as $row) {
if( is_array($row) ) {
getSingleArray($row); // recursive call -> row it cand be also multi dimensional
}
else {
$singleArray[] = $val;
}
}
return $singleArray;
}
I really hope this will help!!

Related

PHP Array_unique [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Is it possible to remove sub arrays, if the array item at position 0 of that sub array matches subsequent items?
For example;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 )
[1] => Array ( [0] => 1234 [1] => XX001 )
[2] => Array ( [0] => 1234 [1] => XX002 )
)
Would be adjusted to output;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 ) )
function my_array_filter($arr){
$exist = [];
return array_filter($arr, function($element){
if( ! array_key_exist($element[0], $exist)){
$exist[$element[0]] = true;
return true;
}
return false;
});
}
Maybe it is possible with some arcane usage of array functions and callback, but I prefer keeping things simple whenever possible, so I understand my own solutions years later.
So why not program it?
$ORG = [ [ 1234, 'XX000' ],
[ 1234, 'XX001' ],
[ 1234, 'XX002' ],
[19987, 'XX000'] ];
$NEW = [];
$USEDKEYS = [];
foreach ($ORG as $one){
if (in_array($one[0], $USEDKEYS)) {
// skip.
} else {
$NEW[] = $one;
$USEDKEYS[] = $one[0];
}
}
unset ($USEDKEYS, $ORG);
var_dump ($NEW);
Always the way, I've found out the solution after posting this ($query being the multi-dimensional array);
$newArr = array();
foreach ($query as $val) {
$newArr[$val[0]] = $val;
}
$query = array_values($newArr);

How to change array key of this array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In PHP, how do you change the key of an array element?
This the array
Array
(
[0] => Array
(
[id] => 1
[due_date] => 2011-09-23
[due_amount] => 10600.00
)
[1] => Array
(
[id] => 2
[due_date] => 2011-10-23
[due_amount] => 10600.00
)
[2] => Array
(
[id] => 3
[due_date] => 2011-11-23
[due_amount] => 10600.00
)
)
how to change id to u_id in this array?
Regards
array_walk_recursive($array, 'changeIDkey');
function changeIDkey($item, &$key)
{
if ($key == 'id') $key = 'u_id';
}
PHP Manual: array_walk_recursive
EDIT
This will not work for the reason #salathe gave in the Comments below. Working on alternative.
ACTUAL ANSWER
function changeIDkey(&$value,$key)
{
if ($value === "id") $value = "u_id";
}
$new = array();
foreach ($array as $key => $value)
{
$keys = array_keys($value);
array_walk($keys,"changeIDkey");
$new[] = array_combine($keys,array_values($value));
}
var_dump($new); //verify
Where $array is your input array. Note that this will only work with your current array structure (two-dimensions, changes keys on only second dimension).
The loop iterates through the inner arrays changing "id" to "u_id" in the keys and then recombines the new keys with the old values.
foreach( $array as &$element ) {
$element['u_id'] = $element['id'];
unset( $element['id'] );
}

Multidimensional array unique based on value (not array key) [duplicate]

This question already has answers here:
How can you make a multidimensional array unique? [duplicate]
(6 answers)
Closed 10 years ago.
I have a multidimensional array which I need to be sorted with uniqueness as I have duplicated records, so I need array_unique to go through the array and remove duplicates by the value, e.g.
Array
(
[0] => Array
(
[id] => 324
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
[1] => Array
(
[id] => 325
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
[2] => Array
(
[id] => 326
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
)
There are duplicated time_start, which they are all the same, also level and input_level but they are not to be affected, only if there are matching time_start it should remove it and process the whole array (the array is bigger than you think, but I just posted a small example of the array). Should remove dupes and return like this:
Array
(
[0] => Array
(
[id] => 324
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
)
Questions I've found that didn't work:
reformat multidimensional array based on value
Delete element from multidimensional-array based on value
$input = array( /* your data */ );
$temp = array();
$keys = array();
foreach ( $input as $key => $data ) {
unset($data['id']);
if ( !in_array($data, $temp) ) {
$temp[] = $data;
$keys[$key] = true;
}
}
$output = array_intersect_key($input, $keys);
or
$input = array( /* your data */ );
$temp = $input;
foreach ( $temp as &$data ) {
unset($data['id']);
}
$output = array_intersect_key($input, array_unique($temp));
$temp = array();
array_filter($yourArray, function ($v) use (&$temp) {
if (in_array($v['time_start'], $temp)) {
return false;
} else {
array_push($temp, $v['time_start']);
return true;
}
});
Uses array_filter() which will filter an array based on the result of a callback (I used an anonymous function which can be used since PHP 5.3). The time_start values are collected into a temporary array.
I think you'll just have to walk it:
$usedVals = array();
$outArray = array();
foreach ($targetArray as $arrayItem)
{
if (!in_array($arrayItem['time_start'],$usedVals))
{
$outArray[] = $arrayItem;
$usedVals[] = $arrayItem['time_start'];
}
}
return $outArray;
$uniq = array();
foreach($no_unique as $k=>$v) if(!isset($uniq[$v['time_start']])) $uniq[$v['time_start']] = $v;
$uniq = array_values($uniq);

PHP : flatten array - fastest way? [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 5 months ago.
Is there any fast way to flatten an array and select subkeys ('key'&'value' in this case) without running a foreach loop, or is the foreach always the fastest way?
Array
(
[0] => Array
(
[key] => string
[value] => a simple string
[cas] => 0
)
[1] => Array
(
[key] => int
[value] => 99
[cas] => 0
)
[2] => Array
(
[key] => array
[value] => Array
(
[0] => 11
[1] => 12
)
[cas] => 0
)
)
To:
Array
(
[int] => 99
[string] => a simple string
[array] => Array
(
[0] => 11
[1] => 12
)
)
Give this a shot:
$ret = array();
while ($el = each($array)) {
$ret[$el['value']['key']] = $el['value']['value'];
}
call_user_func_array("array_merge", $subarrays) can be used to "flatten" nested arrays.
What you want is something entirely different. You could use array_walk() with a callback instead to extract the data into the desired format. But no, the foreach loop is still faster. There's no array_* method to achieve your structure otherwise.
Hopefully it will help someone else, but here is a function I use to flatten arrays and make nested elements more accessible.
Usage and description here:
https://totaldev.com/flatten-multidimensional-arrays-php/
The function:
// Flatten an array of data with full-path string keys
function flat($array, $separator = '|', $prefix = '', $flattenNumericKeys = false) {
$result = [];
foreach($array as $key => $value) {
$new_key = $prefix . (empty($prefix) ? '' : $separator) . $key;
// Make sure value isn't empty
if(is_array($value)) {
if(empty($value)) $value = null;
else if(count($value) == 1 && isset($value[0]) && is_string($value[0]) && empty(trim($value[0]))) $value = null;
}
$hasStringKeys = is_array($value) && count(array_filter(array_keys($value), 'is_string')) > 0;
if(is_array($value) && ($hasStringKeys || $flattenNumericKeys)) $result = array_merge($result, flat($value, $separator, $new_key, $flattenNumericKeys));
else $result[$new_key] = $value;
}
return $result;
}
This should properly combine arrays with integer keys. If the keys are contiguous and start at zero, they will be dropped. If an integer key doesn't yet exist in the flat array, it will be kept as-is; this should mostly preserve non-contiguous arrays.
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key)
{
if (array_key_exists($key, $flat))
{
if (is_int($key))
{
$flat[] = $value;
}
}
else
{
$flat[$key] = $value;
}
});
return $flat;
}
You could use !isset($key) or empty($key) instead to favor useful values.
Here's a more concise version:
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key) use (&$flat)
{
$flat = array_merge($flat, array($key => $value));
});
return $flat;
}

How do i sort multidimension array in PHP? [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 months ago.
I have array like
Array (
[608665839] => Array ( [score] => 2 )
[1756044141] => Array ( [score] => 5 )
[523536777] => Array ( [score] => 2 )
)
and I want to sore this array by score. How can I do?
I would use uasort
I think [uasort()]1 function is helpful for sorting this array()
If multiple array then use array_[multisort()]2 functions
From PHP.net:
<?php
function order_array_num ($array, $key, $order = "ASC")
{
$tmp = array();
foreach($array as $akey => $array2)
{
$tmp[$akey] = $array2[$key];
}
if($order == "DESC")
{arsort($tmp , SORT_NUMERIC );}
else
{asort($tmp , SORT_NUMERIC );}
$tmp2 = array();
foreach($tmp as $key => $value)
{
$tmp2[$key] = $array[$key];
}
return $tmp2;
}
?>
$order = "ASC" will sort the array in an ascending order while $order = "DESC" will sort the array in a descending order.
Hope this helps.

Categories