how to get key of a value that in array of array? - php

I can't deal with this. Please help me. This is array:
$arr = array("data" => array(
array("id" => "5451"),
array("id" => "45346346")
));
for example how can i find the key for id 45346346 ?
$key = array_search($arr['data'], 45346346);
I have tried this but its not working.
I'm trying to delete that array line. I'm guessing I can do that with unset($key)

You have an array of array of arrays. $arr['data'] is an array with 2 values. These values are both arrays. array_search doesn't work, as 45346346 doesn't match an array.
You'd have you cook your own search, something like this:
function find_in_array($arr, $val){
$found = false;
foreach($arr as $k=>$x){
if(array_search($val, $x) !== FALSE){
$found = $k;
break;
}
}
return $found;
}
Then you can do: $key = find_in_array($arr['data'], 45346346);. This will return 1, the index of the array containing 'id' => 45346346 inside $arr['data'].
DEMO: http://codepad.org/pSxaBT9g

Related

Multidimensional array - replace

I have an array, similar to the following:
$array = [
['file' => 1, 'status' => 'pending'],
['file' => 2, 'status' => 'pending'],
];
What I want to do is to replace the statuspart, where the file is 1
I'm not sure if i can do this in a simple array, or using an in-built array_ method
I have something liek the following so far:
$data = [];
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$data['status'] = 'updated';
}
}
You're close, but as $data is array of arrays, you need to provide $arr as top-level key and even get rid of second array:
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$array[$arr]['status'] = 'updated';
}
}
This should give you an idea of how to tackle that.
if ($array[0]['file'] == 1) {
$array[0]['whatever'] = $array[0]['status'];
unset($array[0]['status']);
}
The 0 can ofcourse be changed by i in a loop if you wish to cycle through the entire array.

Group subarrays by one column, make comma-separated values from other column within groups

I have a array that looks like this:
$array = [
["444", "0081"],
["449", "0081"],
["451", "0081"],
["455", "2100"],
["469", "2100"]
];
I need to group as a new array that looks like:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
I'd tried many scripts, but with no success.
function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
$newArray = _group_by($array, 1); // (NO SUCCESS)
There should be more elegant solutions, but simplest one I can think of would be this.
// The data you have pasted in the question
$data = [];
$groups = [];
// Go through the entire array $data
foreach($data as $item){
// If the key doesn't exist in the new array yet, add it
if(!array_key_exists($item[1], $groups)){
$groups[$item[1]] = [];
}
// Add the value to the array
$groups[$item[1]][] = $item[0];
}
// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
// With the array built in the last loop, implode it with a comma
// Also add the 'key' from the last array to it ($group)
$structured[] = [implode(',', $values), $group];
}
I haven't tested this but something similar should do the trick. This simply goes through the given array and collects all entries in a structurized manner (so $groups variable will contain an array entry for each group sharing a key, and the key will correspond to the 2nd item in each item within the given array). From there it's just about restructuring it to get the format you have requested.
http://php.net/manual/en/control-structures.foreach.php
Writing two loops is too much effort for this task. Use isset() with temporary keys applied to your output array as you iterate. When finished grouping the data, reindex the output with array_values().
Code (Demo)
$array = [
["444", "0081"],
["449", "0081"],
["451", "0081"],
["455", "2100"],
["469", "2100"]
];
foreach ($array as $row) {
if (!isset($result[$row[1]])) {
$result[$row[1]] = $row; // first occurrence of group, save whole row
} else {
$result[$row[1]][0] .= ',' . $row[0]; // not first occurrence, concat first element in group
}
}
var_export(array_values($result));
Or avoid the temporary associative arrays in the result array by using an array of references. (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($ref[$row[1]])) {
$ref[$row[1]] = $row;
$result[] = &$ref[$row[1]];
} else {
$ref[$row[1]][0] .= ',' . $row[0];
}
}
var_export($result);
Or use array_reduce() to enjoy a functional-style technique. (Demo)
var_export(
array_values(
array_reduce(
$array,
function($result, $row) {
if (!isset($result[$row[1]])) {
$result[$row[1]] = $row;
} else {
$result[$row[1]][0] .= ',' . $row[0];
}
return $result;
}
)
)
);
All will output:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)

Combine two array in php

I have two array in php and now I want to combine this two array as below.
$a1 = Array(
'ansid4' => 4,
'ansid5' => 5,
'ansid6' => 6
);
$a2 = Array(
'value' => 'demo',
'value2' => 'demo2'
);
Required Output:
$target = Array(
4 => 'demo',
5 => 'demo2',
6 => Null
);
Thanks in advance
$resultArray = array();
while ($key = array_pop($arrayOne)) {
$resultArray[$key] = array_pop($arrayTwo);
}
or you could do
$resultArray = array();
foreach ($arrayOne as $key) {
$resultArray[$key] = array_shift($arrayTwo);
}
Both solutions have the disadvantage that they consume one or both arrays.
If you need them still after the combination you could make copies of the Arrays and have those consumed.
Take a look at array_combine
you can send to this function array of keys and array of values and it return assoc array
please notice that the two arrays must have the same number of elements.
if you cant take care of that, try using array_pad before
$targetArray = array('a'=>'','b'=>'');
$sourceArray = array('a'=>array(1,2,3),'c'=>'c','d'=>'d');
$result = array_merge( $targetArray, $sourceArray);
$array_text = recurse_array($result);
echo $array_text;
function recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
You have to have the same number of elements in both arrays so we start with counting of elements and add necessary NULL values by array_pad
if (count($a1) > count($a2))
{
$a2 = array_pad1($a2, count($a1), NULL);
}
elseif (count($a1) < count($a2))
{
$a1 = array_pad($a1, count($a2), NULL);
}
Then we use array_combine, which creates new array. From both arrays we use values by array_values. From first array we use values as keys and from second array we use values as values:-)
$target = array_combine(array_values($a1), array_values($a2))

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

Searching nested arrays and returning the key from a matching value

[
[mile] => [
[acronym] => mi
],
[kilometer] => [
[acronym] => km
]
]
$acronym = 'km';
How may I return the key name from a matching acronym value? In this example I want to return kilometer.
This should work for you:
Here I just simply create an array with array_combine() where I use the array_column() with the keyname acronym as keys and the array_keys() from the $arr as values.
<?php
$acronym = "km";
$arr = array_combine(array_column($arr, "acronym"), array_keys($arr));
echo $arr[$acronym];
?>
output:
kilometer
You can do something like
$array = array(
'mile'=>array('acronym'=>'mi'),
'kilometer'=>array('acronym'=>'km')
);
$acronym = 'km';
function get($each,$acronym)
{
foreach($each as $k => $v)
{
if($v['acronym'] == $acronym)
{
return $k;
}
}
}
get($array,$acronym);
If your array can have multiple levels, you can use a stack, and you recursively enumerate through the array, and when you encounter an acronym key, you have the full key path in the stack. Something like this:
function findAcronym($array, $keyStack, &$result) {
foreach($array as $key => $value) {
if($key === 'acronym') {
$result[] = $keyStack;
} elseif(is_array($value)) {
$keyStack[] = $key;
findAcronym($value, $keyStack, $result)
}
}
}
you can use the function like this:
$matches =[];
findAcronym($myArray, [], $matches);
$matches will be an array of array of keys, each array of keys corresponding to the key path that gets you to the acronym one.
As the function is recursive, it can go as deep as many levels the array has.

Categories