Search and get Key in Multidimensional Array - php

I have multidimensional array and I need to search for top level key by the value in "add_fields" arrays by "value". I cannot figure out I can achieve the result. Can somebody help me?
I was googling it and found several solutions but I was not able to get any result.
Trying this code
array_search('001001', array_column(array_column($arr, "usr_column_504"), 0)),
but didn't get anything and I need to get top level key. In this example its 0;
array (
0 =>
array (
'id' => 1,
'group_id' => 327,
'volume' => 0,
'vat' => 1,
'order_id' => 1,
'add_fields' =>
array (
1 =>
array (
'field' => 'usr_column_501',
'value' => '',
),
2 =>
array (
'field' => 'usr_column_504',
'value' => '001001',
),
),
),
1 =>
array (
'id' => 2,
'group_id' => 327,
'vat' => 1,
'order_id' => 2,
'add_fields' =>
array (
1 =>
array (
'field' => 'usr_column_501',
'value' => '',
),
2 =>
array (
'field' => 'usr_column_504',
'value' => '001002',
),
),
),
)

If you want the first key where the value of field equals usr_column_504 you could use an outer and an inner foreach.
When the value of field is found, return the $key from the outer foreach.
foreach ($arr as $key => $item) {
foreach ($item["add_fields"] as $addField) {
if ($addField["field"] === "usr_column_504") {
echo $key;
return;
}
}
}
Output
0
Php demo

Related

How can i access all values within a nested array in php by defining a specific key?

I am creating an routing application and get the result as an json array. After transforming it into an php array i get the whole distance and whole duration correctly. Now i need for every value in the key "legs" the distances and durations too but all i did to get the data doesnt work.
The json output of the array looks like this:
array (
'routes' =>
array (
0 =>
array (
'legs' =>
array (
0 =>
array (
'summary' => '',
'weight' => 3741.9,
'duration' => 2912.3, // This value is what i want access
'steps' =>
array (
),
'distance' => 21603.1, // This value is what i want access
),
1 =>
array (
'summary' => '',
'weight' => 3642.1,
'duration' => 2777.4, // This value is what i want access
'steps' =>
array (
),
'distance' => 21611.8, // This value is what i want access
),
),
'weight_name' => 'routability',
'weight' => 7384,
'duration' => 5689.700000000001, // This value i can acesss
'distance' => 43214.899999999994, // This value i can acesss too
),
),
'waypoints' =>
array (
0 =>
array (
'hint' => '',
'distance' => 16.78277948979663, // This value is what i want access
'name' => 'Weg',
'location' =>
array (
0 => 11.4623,
1 => 50.7126,
),
),
1 =>
array (
'hint' => '',
'distance' => 16.62835508134535,
'name' => 'Weg',
'location' =>
array (
0 => 12.6069,
1 => 51.5398,
),
),
2 =>
array (
'hint' => '',
'distance' => 16.78277948979663,
'name' => 'Weg',
'location' =>
array (
0 => 12.343,
1 => 51.576,
),
),
),
'code' => 'Ok',
)
The whole distance (43214.8) and whole duration (5689.7) i get by the following code:
foreach($res2['routes'] as $item)
{
$distances = array_push_assoc($distances, $item['distance'], $item['duration']);
}
In order to get the distances and durations i did the following:
foreach($res2['routes']['legs'] as $item)
{
$durations = array_push_assoc($durations , "DUR", $item['duration']);
}
How can i get the distances and durations from "legs"? Why doenst work $res2['routes']['legs']?
Thank you!
Do notice the the "legs" array exists in index 0 of the "routes" array so looping on it will require using $res2['routes'][0]['legs'].
Morever, notice that using array_push_assoc in loop with the same hard-coded key (as "DUR" in your example) will override the key each time so your data gets lost - you better change it to:
foreach($res2['routes'][0]['legs'] as $item) {
$durations[] = $item['duration'];
}

If array value is repeated in another array, combine both arrays

I have several arrays that I want to check for a repeated value and if the value is found to be repeated in one of the other arrays, then combine both of those arrays together.
I give an example below of 2 arrays that have repeated values.
example: the value in purchase_order_number is the same in both arrays below. They are not unique values. But the values in tracking_number are unique.
I want to check if the value in purchase_order_number is repeated in another array. If the same value is found in another array, then combine both of those arrays into 1 array.
I'm trying to get the value in tracking_number and service combined into a single array when the value in purchase_order_number is the same in 2 or more arrays.
Example arrays below.
not combined
array (
'data' =>
array (
15 =>
array (
'type' => 'Tracking',
'id' => 2830143,
'attributes' =>
array (
'tracking_number' => '1Z5270560360309870',
'service' => 'UPS',
'order_id' => 2606218,
'purchase_order_number' => '7249491',
'recipient_attempts' => 1,
),
),
16 =>
array (
'type' => 'Tracking',
'id' => 2830144,
'attributes' =>
array (
'tracking_number' => '1Z5270560361740866',
'service' => 'UPS',
'order_id' => 2606218,
'purchase_order_number' => '7249491',
'recipient_attempts' => 1,
),
),
),
)
Example given below of how I need to combine the two above arrays.
Combined
array (
'data' =>
array (
16 =>
array (
'type' => 'Tracking',
'id' => 2830144,
'attributes' =>
array (
'tracking' =>
array (
0 =>
array (
'tracking_number' => '1Z5270560360309870',
'service' => 'UPS',
),
1 =>
array (
'tracking_number' => '1Z5270560361740866',
'service' => 'UPS',
),
),
'order_id' => 2606218,
'purchase_order_number' => '7249491',
'recipient_attempts' => 1,
),
),
),
)
Here's a reduce based solution with caveats:
$arr['data'] = array_reduce($arr['data'], function ($out, $item) {
// keys we want to extract
static $tracking_keys = ['tracking_number' => '', 'service' => ''];
// yank tracking keys from attributes
$tracking = array_intersect_key($item['attributes'], $tracking_keys);
$item['attributes'] = array_diff_key($item['attributes'], $tracking_keys);
// insert to new array based on order number
$order_no = $item['attributes']['purchase_order_number'];
if (!isset($out[$order_no])) {
$item['attributes']['tracking'] = [$tracking];
$out[$order_no] = $item;
} else {
array_push($out[$order_no]['attributes']['tracking'], $tracking);
}
return $out;
}, []);
Keys in 'data' are not retained and 'id' is set by the first item.

Finding duplicate values in a multidimensional array for Search Method

My Code was :
$data = array();
foreach ($table as $key => $var) {
$data[] = ['id' => $var->id, 'value' => $var->designation];
}
My Data array should be like this
array (
0 => array (
'id' => 27,
'value' => 'laravel',
),
1 => array (
'id' => 1,
'value' => 'laravel tester',
),
2 => array (
'id' => 22,
'value' => 'laravel developer',
),
3 => array (
'id' => 23,
'value' => 'laravel casts',
),
4 => array (
'id' => 24,
'value' => 'laravel developer',
),
)
I need only one value i tried all the php core library function output:
array (
0 =>
array (
'id' => 27,
'value' => 'laravel',
),
1 => array (
'id' => 1,
'value' => 'laravel tester',
),
2 => array (
'id' => 23,
'value' => 'laravel casts',
),
3 => array (
'id' => 24,
'value' => 'laravel developer',
),
)
Based on the name only i need to remove duplicate bacause in my search bar it shows repeated mode.
You can use array_unique, wich saves indexes, and get the result by array_intersect_key
$temp = array_unique(array_column($arr, 'value'));
$res = array_intersect_key($arr, $temp);
print_r($res);

PHP multidimensional array search with provided array column (using PHP5 array_column)

I need help with array search. The array example is:
$users=Array
(
0 => Array
(
'id' => 111,
'name' => 'Sandra Shush',
'sources' => '1234,678,780'
),
1 => Array
(
'id' => 112,
'name' => 'Stefanie Mcmohn',
'sources' => '32,99,85'
),
2 => Array
(
'id' => 113,,
'name' => 'Michael',
'sources' => '896,1213,1918'
),
3 => Array
(
'id' => 113,,
'name' => 'Michael',
'sources' => '72'
)
);
I need to extract the key from the provided array above, where the "sources" key matches the search string (integer).
I've tried with:
$key = array_search('99', array_column( $users, 'sources') ); // false
But of course, there's no chance to retrieve the key with this method. It only works if source key has only one value, for example:
$key = array_search('72', array_column( $users, 'sources') ); // 3
Is there a way to achieve this?
Thank you
Simply use foreach loop along with preg_match like as
$result = [];
foreach($users as $key => $value){
if(preg_match("/\b99\b/",$value['sources']) !== false){
$result[] = $key;
}
}
print_r($result);
Output:
Array
(
[0] => 1
)
Demo

Change index of an array

I want to change the index of an array but I don't know how to do it..
The following array
array(
0 => array ( 'id' => 33, 'name' => 'test' )
1 => array ( 'id' => 37, 'name' => 'test2' )
)
should become - if i want the index
array(
33 => array ( 'id' => 33, 'name' => 'test' )
37 => array ( 'id' => 37, 'name' => 'test2' )
)
or if i want the name
array(
test => array ( 'id' => 33, 'name' => 'test' )
test2 => array ( 'id' => 37, 'name' => 'test2' )
)
also for a multi-dimensional array
array(
0 => array ( 'id' => 33, 'details' => array (name => 'test' , age ='50' ) )
1 => array ( 'id' => 37, 'details' => array (name => 'test2' , age ='60' ) )
)
to index replace 0 and 1 with the name - test or test2
right now I made a function but is not working with multi dimensional arrays
function index_array( $array, $index ){
$new_array = array();
foreach($array as $key => $value){
$new_array[$index] = $array[$key];
}
return $new_array;
}
$array = array(33 => $oldarray[0], 37 => $oldarray[1]);
$array = array('test' => $oldarray[0], 'test2' => $oldarray[1]);
Since the right-hand-side of the expression is evaluated before the assignment you could also use $array on both sides instead of a different variable name.
I'd do it with a mapping table for the first part, or a simple foreach for the second part:
<?php
$arr = array(
0 => array( 'id' => 33, 'name' => 'test' ),
1 => array( 'id' => 37, 'name' => 'test2' )
);
/* Convert to other indexes */
$mapping = array(
0 => 33,
1 => 37
);
foreach($arr as $k => $v){
unset($arr[$k]);
$arr[$mapping[$k]] = $v;
}
print_r($arr);
/* Convert key to name field */
foreach($arr as $k => $v){
unset($arr[$k]);
$arr[$v['name']] = $v;
}
print_r($arr);
EDIT: Now that I read your question again, the first part is actually the same as the second, but then just with the id field instead of the name field.
EDIT2: Note that you'd have to use another array to write to, to avoid overrides, which will occur when the id field is used as a replacement.

Categories