sorting a php array - php

how do i sort this array by the nums...
Array(
[nums] => Array
(
[0] => 34
[1] => 12
[2] => 13
)
[players] => Array
(
[0] => Mike
[1] => Bob
[2] => Mary
)
)
... so that i get this one?
Array(
[nums] => Array
(
[0] => 12
[1] => 13
[2] => 34
)
[players] => Array
(
[0] => Bob
[1] => Mary
[2] => Mike
)
)

array_multisort($x['nums'],$x['players']);

Try the sort function.
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Also check out asort and arsort
EDIT
I did not take into account your Multidimensional array.
<?php
//code derived from comments on the php.net/sort page.
// $sort used as variable function--can be natcasesort, for example
function sort2d( &$arrIn, $index = null, $sort = 'sort') {
// pseudo-secure--never allow user input into $sort
if (strpos($sort, 'sort') === false) {$sort = 'sort';}
$arrTemp = Array();
$arrOut = Array();
foreach ( $arrIn as $key=>$value ) {
reset($value);
$arrTemp[$key] = is_null($index) ? current($value) : $value[$index];
}
$sort($arrTemp);
foreach ( $arrTemp as $key=>$value ) {
$arrOut[$key] = $arrIn[$key];
}
$arrIn = $arrOut;
}
?>

Related

How to move a value up to a key, and remove a key. Array manipulation

I'm trying to change my array from this:
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
in to this:
Array
(
[BID_OPEN]
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE]
(
[0] => 1.654545
[1] => 1.645845
)
)
I'm not sure how to begin. My code:
foreach($array as $keys=>$values)
{
if(!empty($array [$c]['BID_OPEN']))
{
$inital_part1 = array("BID_OPEN", $array [$c]['BID_OPEN']);
}
else
{
echo '';
}
if(!empty($array [$c]['BID_CLOSE']))
{
$inital_part2 = array("BID_CLOSE", $array [$c]['BID_CLOSE']);
}
else
{
echo '';
}
$array1[] = $inital_part1;
$array1[] = $inital_part2;
$c++;
}
I seem to get double outputs, so the foreach when I build arrays is giving me two times the required output. Google reckons it's because I have an array in my array somewhere but I'm precisely sure I don't.
The array came from an object stdclass and I don't know what that is, have googled but haven't found anything useful. Also I'm able to get some figures but only the initial values are correct, the rest of the data doesn't seem to come through. No doubt it's because I used an index[0] to get it working.
After hours any help would be great thanks.
As long as you have told us everything about your input array it can be done quite simply like this
<?php
$in = [ ['BID_OPEN' => [0.718282]],
['BID_CLOSE' => [1.654545]],
['BID_OPEN' => [1.654878]]
];
print_r($in);
$new = []; // new array we are building
foreach ($in as $abid) {
if (array_key_exists('BID_OPEN', $abid) ) {
$new['BID_OPEN'][] = $abid['BID_OPEN'][0];
}
if (array_key_exists('BID_CLOSE', $abid) ) {
$new['BID_CLOSE'][] = $abid['BID_CLOSE'][0];
}
}
print_r($new);
THE INPUT ARRAY: Is like yours
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
RESULT:
Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
$c = 0;
$array1['BID_OPEN'] = [];
$array2['BID_CLOSE'] = [];
foreach($vartttttt as $tunips=>$ert)
{
$d = 0;
foreach($ert as $erts=>$val)
{
//$array[] = $erts;
if($erts == 'BID_OPEN')
{
array_push($array1['BID_OPEN'], $val[0]);
}
if($erts == 'BID_CLOSE')
{
array_push($array2['BID_CLOSE'], $val[0]);
}
$d++;
}
$c++;
}
$array = array_merge($array1, $array2);

group php array by subarray value

I want to group an array by a subarray's value. If I have an array like this:
Array
(
[0] => Array
(
[userID] => 591407753
[propertyA] => 'text1'
[propertyB] => 205
)
[1] => Array
(
[userID] => 989201004
[propertyA] =>'text2'
[propertyB] => 1407
)
[2] => Array
(
[userID] => 989201004
[propertyA] => 'text3'
[propertyB] => 1407
)
)
I want to sort to group this array by a subarray's value so I can have an array like this:
Array
(
[0]=>Array
(
[userID]=>59140775
[properties]=>Array
(
[0]=>text1
)
[propertyB]=>205
)
[1]=>Array
(
[userID]=>989201004
[properties]=>Array
(
[0]=>'text2'
[1]=>'text3'
)
[propertyB]=>1047
)
)
How can I make this?
Before I had tried this:
$result = array();
foreach ($userArray as $record)
{
$id=$record['userID'];
if(isset($result[$id]))
{
$result[$id]['propertyA'][]=array($record['propertyA']);
}
else {
$record["propertyA"]=array($record['propertyA']);
unset($record['tweet']);
$result[$id]=$record;
}
}
the problem was for the propertyA. I was an the result an additional property propertyA with the table like this:
Array
(
[0]=>Array (
[userID]=>989201004
[propertyA]=>'text2'
[properties]=>Array(
[0]=>'text2'
[1]=>'text3'
)
)
)
The following code should do the job. I hope it is self-explanatory:
$result = array();
foreach ($array as $record) {
if (!isset($result[$record['userID']])) {
$result[$record['userID']] = array(
'userID' => $record['userID'],
'properties' => array($record['propertyA']),
'propertyB' => $record['propertyB'],
);
}
else {
$result[$record['userID']]['properties'][] = $record['propertyA'];
}
}
$result = array_values($result);

Creating an array from a string issue

I have a function that creates a multi-dimensional array from a string. Here's how the output looks like for each string:
Strings:
app.name.version
app.vendor
NOTE: These are strings that are being retrieved from a database
Output:
['app']['name']['version']
['app']['vendor']
and I assign them values accordingly. The problem arises when I include numbers in the string representing an index number of a sub array. Here's an example:
shifts.breaks.unpaid.0.description
shifts.breaks.unpaid.0.duration
shifts.breaks.unpaid.1.description
shifts.breaks.unpaid.1.duration
with output:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
)
[1] => Array
(
[duration] => 30
)
[3] => Array
(
[description] => Lunch 2
)
[4] => Array
(
[duration] => 30
)
)
)
Where it should normally look like:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
[duration] => 30
)
[1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
The only thing that remedies this is if I replace the numbers with anything but numerical values like the following:
shifts.breaks.unpaid.b0.description
shifts.breaks.unpaid.b0.duration
shifts.breaks.unpaid.b1.description
shifts.breaks.unpaid.b1.duration
Array
(
[unpaid] => Array
(
[b0] => Array
(
[description] => Lunch
[duration] => 30
)
[b1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
Here's the function that creates the arrays:
function toArray($keys, $value){
$array = array();
$ref = &$array;
while(count($keys) > 0){
$n = array_shift($keys);
if(!is_array($ref))
$ref = array();
$ref = &$ref[$n];
}
$ref = $value;
return $array;
}
Where $keys contains $keys = explode('.', "my.testing.string"); and here's the example I've been working with:
$strings = array (
"app.names.0.first"=> "Samuel",
"app.names.0.last"=> "Smith",
"app.names.1.first" => "Mary",
"app.names.2.last" =>"Kubik"
);
$list = array();
foreach($strings as $key => $name) {
$list[] = (toArray(explode('.', $key),$name));
}
print_r(call_user_func_array('array_merge_recursive', $list));
At this point, I'm not too sure if this has something to do with array_merge_recursive. Any help in correcting this would be great!
Well one solution I found was re-writing a new array_merge_recursive function without overwriting numeric keys.
function array_merge_recursive_new() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base); //important
while (list($key, $value) = #each($array)) {
if (is_array($value) && #is_array($base[$key])) {
$base[$key] = array_merge_recursive_new($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
Thanks to a user on php.net. This will produce the correct output when keys are numeric.

Merge multidimensional arrays in PHP

I would like create a list of values within a new array based on the same keys from the previous array. Basically, I would like to turn this array:
$old_array = Array (
[segment1] => Array (
[subsegment] => Array (
[number1] => 1413
[number2] => 306
)
)
[segment2] => Array (
[subsegment] => Array (
[number1] => 717
[number2] => 291
)
)
)
...into this array:
$new_array = Array (
[segment] => Array (
[subsegment] => Array (
[number1] => Array (
[0] => 1413
[1] => 717
)
[number2] => Array (
[0] => 306
[1] => 291
)
)
)
)
I tried the following:
$new_array = array ();
foreach ($old_array["segment"]["subsegment"] as $value) {
$new_array["segment"]["subsegment"][] = $value;
}
Unfortunately, this doesn't work. What do I need to do? Thanks.
This is very specific to your example $old_array:
$index = 1;
$new_array = array();
do {
if (!isset($old_array["segment" . $index]["subsegment"]))
break;
foreach ($old_array["segment" . $index]["subsegment"] as $key => $value) {
$new_array["segment"]["subsegment"][$key][] = $value;
}
$index++;
} while (true);
I understand you want all number1's in the same key, then all number 2's, and so on. try this:
$numberCount = count($old_array['segment1']['subsegment']);
foreach ($old_array as $segment)
{for ($i=1;$i<=$numberCount;$i++)
{$new_array['segment']['subsegment']['number' . $i][] = $segment['subsegment']['number' . $i];}}
this is assuming all subsegment have the same number of [numberx] keys

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories