I am looking for a way to create a new array based on array contents.
so i've got:
Array ( [0] => 1
[type] => first_value_i_need
[some_id] => 2
[hits] => 88
[some_other_id] => second_value_i_need
)
and i would like to get
Array ( [0] => 1
[app_name] => "first_value_i_need-second_value_i_need"
[hits] => "88"
)
I know that i need some sort of foreach function, but i'm right now lost.
No, you don't need any loops as long as you know which keys you need.
$old = array(
0 => 1,
'type' => 'first_value_i_need',
'some_id' => 2,
'hits' => 88,
'some_other_id' => 'second_value_i_need'
);
$new = array(
0 => $old[0],
'app_name' => $old['type'].'-'.$old['some_other_id'],
'hits' => $old['hits'],
);
So basically do you wnat to get rid of the app_table_id key ?
You can do unset($array['app_table_id']);
And if you need to change some value you can do :
$array['app_name'] = $array['some_other_id'];
//> Note i posted this before your edit.
Related
Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);
This question already has answers here:
Possible to pass a closure to usort in PHP?
(2 answers)
How can I sort arrays and data in PHP?
(14 answers)
Closed 2 years ago.
EDIT: I rewrote my post in order to be clearer and provide a standalone case with real values (no Ajax anymore).
I have 2 arrays that are exactly identical except that one has the same values but cleaned (html, special chars, etc..).
I would like to evaluate the sorting against "arrayClean" but to sort "arrayOriginal" instead (not arrayClean) according to that evaluation.
So, this is what I have:
<?php
$arrayOriginal = array(
array('id' => '100','surface' => '<span>300</span>','whatever' => 'qSDqsd'),
array('id' => '5465','surface' => '100 ch','whatever' => 'ghjkghjk'),
array('id' => '40489','surface' => '<b>1000</b>','whatever' => 'fgsdfg')
);
$arrayClean = array(
array('id' => '100','surface' => '300','whatever' => 'qSDqsd'),
array('id' => '5465','surface' => '100','whatever' => 'ghjkghjk'),
array('id' => '40489','surface' => '1000','whatever' => 'fgsdfg')
);
usort($arrayOriginal, function($a, $b) use (&$arrayClean) {
return $a['surface'] < $b['surface'];
});
echo '<pre>'; print_r($arrayOriginal); echo '</pre>';
?>
here is what I get (which is wrong as the arrayClean doesn't seem to be taken into account for the sorting) :
Array
(
[0] => Array
(
[id] => 100
[surface] => <span>300</span>
[whatever] => qSDqsd
)
[1] => Array
(
[id] => 40489
[surface] => <b>1000</b>
[pwhatever] => fgsdfg
)
[2] => Array
(
[id] => 5465
[surface] => 100 ch
[whatever] => ghjkghjk
)
)
But if I use arrayClean alone, just to check if the sorting script is right:
usort($arrayClean, function($a, $b) {
return $a['surface'] < $b['surface'];
});
echo '<pre>'; print_r($arrayClean); echo '</pre>';
Then the result is what I expect it to be:
Array
(
[0] => Array
(
[id] => 40489
[surface] => 1000
[whatever] => fgsdfg
)
[1] => Array
(
[id] => 100
[surface] => 300
[whatever] => qSDqsd
)
[2] => Array
(
[id] => 5465
[surface] => 100
[whatever] => ghjkghjk
)
)
So it seems that evaluating arrayClean but sorting arrayOriginal accordingly doesn't work. It only evaluates AND sort arrayOriginal.
Do I use "use()" wrong ? Should I use something else ?
Thank you.
Assuming both arrays are sorted by a common factor (i.e. id).
uksort($arrayOriginal, function($a, $b) use ($arrayClean) {
return $arrayClean[$a]['surface'] < $arrayClean[$b]['surface'];
});
Emphasising once more, to make it work, both arrays MUST contain elements in the same order. In your case elements of both arrays MUST come in the following order (by id): 100, 5465, 40489
BUT I'd rather do something like:
usort($arrayOriginal, function($a, $b) {
return yourSurfaceCleanMethod($arrayOriginal['surface']) < yourSurfaceCleanMethod($arrayOriginal['surface']);
});
All depends on your needs, of course, but if you are using $arrayClean only as a reference for sorting original array and you have that yourSurfaceCleanMethod handy, I'd definitely do the above.
I think the arrayClean is not needed if your arrayOriginal should be sorted according to the content of the HTML tags.
strip_tags() can be used for this in your sort function.
usort($arrayOriginal, function($a, $b) {
return strip_tags($b['surface']) <=> strip_tags($a['surface']);
});
Note: Use the spaceship operator <=> to get correct comparison results 1, 0 and -1.
I accepted Nemoden's answer as a courtesy because technically it answered the question according to its scope (the test case as presented). But here is the solution I found that works best for me :
$arrayOriginal = array(
array('id' => '100','surface' => '<span>300</span>','whatever' => 'qSDqsd'),
array('id' => '5465','surface' => '100 ch','whatever' => 'ghjkghjk'),
array('id' => '40489','surface' => '<b>1000</b>','whatever' => 'fgsdfg')
);
$arrayClean = array(
array('id' => '100','surface' => '300','whatever' => 'qSDqsd'),
array('id' => '5465','surface' => '100','whatever' => 'ghjkghjk'),
array('id' => '40489','surface' => '1000','whatever' => 'fgsdfg')
);
$surface = array_column($arrayClean, 'Surface');
array_multisort($surface, SORT_DESC, SORT_REGULAR, $arrayOriginal);
And then I get this output, which is EXACTLY what I want:
Array
(
[0] => Array
(
[id] => 40489
[surface] => <b>1000</b>
[whatever] => fgsdfg
)
[1] => Array
(
[id] => 100
[surface] => <span>300</span>
[whatever] => qSDqsd
)
[2] => Array
(
[id] => 5465
[surface] => 100 ch
[whatever] => ghjkghjk
)
)
The answer of Nemoden was very helpful BUT it gave me this, for whatever reason:
Array
(
[1] => Array
(
[id] => 40489
[surface] => <b>1000</b>
[whatever] => fgsdfg
)
[0] => Array
(
[id] => 100
[surface] => <span>300</span>
[whatever] => qSDqsd
)
[2] => Array
(
[id] => 5465
[surface] => 100 ch
[whatever] => ghjkghjk
)
)
The sub arrays are PRINTED in the right order but the sub arrays indexes weren't changed. So when exporting to javascript "arrayOriginal", it would come back to its initial sorting because the sub arrays would be re-ordered according to their indexes again. At least, that's what I experienced.
Anyway, now the problem is solved and the answers I got here were very helpful.
Thank you.
I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,
[services] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[package_type] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[service_desc] => Array
(
[0] => Full HD
[1] => Full HD
[2] => Full HD
)
[service_price] => Array
(
[0] => 500
[1] => 600
[2] => 500
)
Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0], service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?
array_map is key here. Leave the first argument as null and it will group as you want:
<?php
$data =
[
'services' =>
[
'programming',
'debugging'
],
'description' =>
[
'the process of writing computer programs.',
'the process of identifying and removing errors from software/hardware'
]
];
$result = array_map(null, $data['services'], $data['description']);
var_export($result);
Output:
array (
0 =>
array (
0 => 'programming',
1 => 'the process of writing computer programs.',
),
1 =>
array (
0 => 'debugging',
1 => 'the process of identifying and removing errors from software/hardware',
),
)
Instead of writing out all your keys as arguments you could unpack like this:
array_map(null, ...array_values($data));
For something more elaborate, pass array_map a callable:
$keys = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
return array_combine($keys, $args);
}, ...array_values($data));
var_export($result);
Output:
array (
0 =>
array (
'services' => 'programming',
'description' => 'the process of writing computer programs.',
),
1 =>
array (
'services' => 'debugging',
'description' => 'the process of identifying and removing errors from software/hardware',
),
)
I have an array like this:
[0] => Array
(
[id_station] => 2397
[hour] => 12
[data] => Array
(
[cameraon] => 355654
[cameraoff] => 4532
[camerabroken] => 76745
...
)
)
[1] => Array
(
[id_station] => 2399
[hour] => 13
[data] => Array
(
[cameraon] => 3905466
[cameraoff] => 1672
[camerabroken] => 70780
...
)
)
I want to add one more row = total of all items
[1] => Array
(
[id_station] =>
[hour] =>
[data] => Array
(
[cameraon] => 4261120
[cameraoff] => 6204
[camerabroken] => 147525
)
)
I used array_sum(array_column($array["data], 'cameraon')) but I have to do for all items cameraon, cameraoff, camerabroken (I have a hundred items).
Is there any way to get total row in this case?
I assume that you don't know the depth of data sub-array. (that is how many key-value pairs are there)
So do like below:-
$final_array = [];
$final_array['id_station'] ='';
$final_array['hour'] ='';
foreach($original_array as $original_arr){
foreach($original_arr['data'] as $key=>$original){
$final_array['data'][$key] +=$original;
}
}
Output:-https://eval.in/926729
You wish to sum the columnar data, so leveraging array_sum() and array_column() are wise choices. The only thing left to do is set up the loop.
You can first isolate the data subarrays using array_column() then "drill down" into the first subarray to iterate each column. Use the column names to access all values in all columns. This makes the method dynamically successful regardless of the complexity of your data subarrays.
Code: (Demo)
$array=[
[
'id_station'=>2397,
'hour'=>12,
'data'=>['cameraon'=>355654,'cameraoff'=>4532,'camerabroken'=>76745]
],
[
'id_station'=>2399,
'hour'=>14,
'data'=>['cameraon'=>3905466,'cameraoff'=>1672,'camerabroken'=>70780]
]
];
$datas=array_column($array,'data'); // isolate the data subarrays
foreach(current($datas) as $column=>$data){ // iterate the columns
$result[$column]=array_sum(array_column($datas,$column)); // sum the column values
}
$array[]=['id_station'=>'','hour'=>'','data'=>$result]; // completenew item and append
var_export($array); // print to screen
Output:
array (
0 =>
array (
'id_station' => 2397,
'hour' => 12,
'data' =>
array (
'cameraon' => 355654,
'cameraoff' => 4532,
'camerabroken' => 76745,
),
),
1 =>
array (
'id_station' => 2399,
'hour' => 14,
'data' =>
array (
'cameraon' => 3905466,
'cameraoff' => 1672,
'camerabroken' => 70780,
),
),
2 =>
array (
'id_station' => '',
'hour' => '',
'data' =>
array (
'cameraon' => 4261120,
'cameraoff' => 6204,
'camerabroken' => 147525,
),
),
)
I’m trying to do a function in php that try to make an intersection of an array of arrays. I have found array_intersect($resultx,$resulty); but it's working just for tables with one value. In my case I have arrays of arrays like that.
Array
(
[0] => Array
(
[name] => Chris
[id] => 1033
)
[1] => Array
(
[name] => Vins
[id] => 1034
)
[2] => Array
(
[name] => Steve
[id] => 1035
)
[3] => Array
(
[name] => Henry
[id] => 1036
)
[4] => Array
(
[name] => Jack
[id] => 1037
)
[5] => Array
(
[name] => Paul
[id] => 1038
)
)
To resume my problem I’m trying to make an intersection of lot of tables like the one i have mentioned. So any idea
examples tab1[[1,2,3],[2,3,1]] tab2[[1,2,3],[5,7,7] the result will be tab3[[1,2,3]] it is clear for you ?
Thanks
#KANDROID OS, Please check below example for intersection of arrays.
Suppose you have two array(s) like below:
$arr1 = array(
array('name' => 'Chris','id' => '1111'),
array('name' => 'Vins','id' => '1112'),
array('name' => 'Steve','id' => '1113'),
);
$arr2 = array(
array('name' => 'Chris','id' => '1111'),
array('name' => 'dddd','id' => '2222'),
);
You can use array_uintersect() to use a custom comparison function, like this:
$intersect = array_uintersect($arr1, $arr2, 'comparevalue');
print_r($intersect);
function comparevalue($val1, $val2)
{
return strcmp($val1['id'], $val2['id']);
}
So Outcome of above is like below :
Array
(
[0] => Array
(
[name] => Chris
[id] => 1111
)
)
You could recursively do it like this:
$arr1 = array(
array('name' => 'Chris', 'id' => '1033'),
array('name' => 'Vins', 'id' => '1034'),
array('name' => 'Steve', 'id' => '1035'),
array('name' => 'Henry', 'id' => '1036'),
array('name' => 'Jack', 'id' => '1037'),
);
$find = array( // Array for ANY search criteria,
array(1033), // name, id, etc.
array('Vins') // (Each element needs to be an array)
);
$match = array(); // Define array for results
for($i=0; $i < count($arr1); $i++){ // For every "name/id combo",
for($j = 0; $j < count($find); $j++){ // go through every search criteria
$thisMatch = array_intersect( $arr1[$i], $find[$j]); // and check for a match
if ($thisMatch){ // If a match was found,
$match[] = $arr1[$i]; // add it to the results array
}
}
}
var_dump($match);
This will result in:
Array
[0] =>
Array (
'name' => string 'Chris'
'id' => string '1033'
)
[1] =>
Array (
'name' => string 'Vins' (length=4)
'id' => string '1034' (length=4)
)
You have to be careful though, with the example using the callback, trying to use the intersect for 'name' AND 'id' values WILL NOT return paired values as you might expect. It only needs to find one of the values, so if you try to search for a 'name' that corresponds to a different 'id', you will get both items back, even if that "combination" doesn't exist. It will do the same thing even if you use the keys in the search like this:
$find = array(
array('id' => 1033),
array('name' => 'Vins')
);
I just noticed that issue so I thought I'd bring it up. Depending on what you're trying to do, you may need some sort of recursive aspect anyway, like I've shown.
Hope this helps :)