PHP Array of arrays of arrays - php

I am trying to search this array by the value of ['field'] and then return the value of ['value'] associated with that field in the array.
For example, I want to say "Tell me the value associated with theThirdField".
I've tried many, many permutations of something like the following:
$myVariable = $Array['result']['totalrows'][0]['rownum'][0]['field'];
To further clarify, I will never know which order / sub-array my search field is located in, I only know the string value associated with ['field'].
How would I accomplish this?
Array
(
[result] => Array
(
[totalrows] => 1
[rows] => Array
(
[0] => Array
(
[rownum] => 1
[values] => Array
(
[0] => Array
(
[field] => testMeOnce
[value] => 436586498
)
[1] => Array
(
[field] => testMeTwice
[value] => 327698034
)
[2] => Array
(
[field] => theThirdField
[value] => 108760374
)
[3] => Array
(
[field] => theFourthField
[value] => 2458505
)
[4] => Array
(
[field] => fifthField
[value] => -0.0201
)
)
)
)
)
)

Did you expect something like that?
$needle = 'theThirdField'; // searched field name
$valuesArray = $Array['result']['rows'][0]['values']; //now you have clearer array
array_walk($valuesArray, function($element, $key) use ($needle) {
if ($element['field'] == $needle) {
echo $element['value'];
}
});

I would do something like this, assuming you want to search only in the $myVariable dimension :
$myVariable = $Array['result']['rows'][0]['values'];
foreach ($myVariable as $key => $value) {
if( $value['field'] === 'theThirdField' ) {
echo $value['value'];
break;
}
}

when I ran your code, I got some syntax errors. I have changed your Array to this (changed syntax only):
$a = Array
(
'result' =>
[
'totalrows' => 1,
'rows' =>
[
0 =>
[
'rownum' => 1,
'values' =>
[
0 =>
[
'field' => 'testMeOnce',
'value' => 436586498
],
1 =>
[
'field' => 'testMeTwice',
'value' => 327698034
],
2 =>
[
'field' => 'theThirdField',
'value' => 108760374
],
3 =>
[
'field' => 'theFourthField',
'value' => 2458505
],
4 =>
[
'field' => 'fifthField',
'value' => -0.0201
]
]
]
]
]
);
now you can get the value like this:
print($a['result']['rows'][0]['values'][2]['value']); // --> 108760374
I hope that this is what you are looking for!

Thanks everyone. I used a mix of your suggestions and ended up doing the following:
$valuesArray = $Array['result']['rows'][0]['values'];
foreach ($valuesArray as $value) {
$fieldName = $value['field'];
$$fieldName = $value['value'];
}
Since I know the names of all the fields I want, but not the order, this allowed me to capture all of the values of each field with the name of the field becoming the variable name.

Related

PHP Match by common key of two multidimentional array and merge the two array with both array key [duplicate]

This question already has answers here:
PHP merge two arrays on the same key AND value
(5 answers)
Closed 4 years ago.
Good evening, I have a little bit problem. I have two array. like
$firstArr = Array(
[0] => Array(
[customer_id] => 11,
[home_delivery] => no,
),
[1] => Array(
[customer_id] => 12,
[home_delivery] => no,
),
[2] => Array(
[customer_id] => 13,
[home_delivery] => no,
),
);
$secondArr = Array(
[0] => Array(
[customer_id] => 11,
[test] => no,
[is_active] => yes,
),
[1] => Array(
[customer_id] => 22,
[test] => no,
[is_active] => yes,
),
);
Now i want to get the result like first array's customer_id match with the second array customer_id. Id two array's customer id is same the the value of second array add with first array otherwise the value will be null. Hope guys you got my point what i want. The output which i want is like the below.
$getResult = Array(
[0] => Array(
[customer_id] => 11,
[home_delivery] => no,
[test] => no,
[is_active] => yes,
),
[1] => Array(
[customer_id] => 12,
[home_delivery] => no,
[test] => '',
[is_active] => '',
),
[2] => Array(
[customer_id] => 13,
[home_delivery] => no,
[test] => '',
[is_active] => '',
),
);
I have tried by this code, but it doesnt work. Please help me.
$mergedArray = array();
foreach ($firstArr as $index1 => $value1) {
foreach ($secondArr as $index2 => $value2) {
if ($array1[$index1]['customer_id'] == $array2[$index2]['customer_id']) {
$mergedArray[] = array_merge($firstArr[$index1], $secondArr[$index2]);
}
}
}
echo "<pre>"; print_r($mergedArray); echo "</pre>";
You can do this :
<?php
$results = [];
// Get all unique keys from both arrays
$keys = array_unique(array_merge(array_keys($firstArr[0]), array_keys($secondArr[0])));
// Make array of common customer_ids
foreach (array_merge($firstArr, $secondArr) as $record) {
$results[$record['customer_id']] = isset($results[$record['customer_id']]) ? array_merge($results[$record['customer_id']], $record) : $record;
}
// Fill keys which are not present with blank strings
foreach ($keys as $key) {
foreach ($results as $index => $result) {
if(!array_key_exists($key, $result)){
$results[$index][$key] = '';
}
}
}
print_r($results);
This is how I would do it:
$firstArr = array (
0 =>
array (
'customer_id' => 11,
'home_delivery' => 'no'
),
1 =>
array (
'customer_id' => 12,
'home_delivery' => 'no'
),
2 =>
array (
'customer_id' => 13,
'home_delivery' => 'no'
)
);
$secondArr = array (
0 =>
array (
'customer_id' => 11,
'test' => 'no',
'is_active' => 'yes'
),
1 =>
array (
'customer_id' => 22,
'test' => 'no',
'is_active' => 'yes'
)
);
$secondKey = array_column($secondArr,'customer_id');
foreach($firstArr as &$value){
$idx2 = array_search($value['customer_id'], $secondKey);
$value = array_merge($value, [
'test' => false !== $idx2 ? $secondArr[$idx2]['test'] : '',
'is_active' => false !== $idx2 ? $secondArr[$idx2]['is_active'] : '',
]);
}
print_r($firstArr);
Output:
Array
(
[0] => Array
(
[customer_id] => 11
[home_delivery] => no
[test] => no
[is_active] => yes
)
[1] => Array
(
[customer_id] => 12
[home_delivery] => no
[test] =>
[is_active] =>
)
[2] => Array
(
[customer_id] => 13
[home_delivery] => no
[test] =>
[is_active] =>
)
)
Sandbox
There are 2 "tricks" I use here, the first, and more important one, is array_column this picks just one column from an array, but the thing is the keys in the resulting array will match the original array. Which we can take advantage of.
The array we get from array column looks like this:
array (
0 => 11,
1 => 22
);
Because the keys match the original array we can use array_search (with the ID) to look up that key, which we can then use in the original array. This gives us an "easier" way to search the second array by flattening it out.
So for example when we look up $firstArr['customer_id'] = 11 in the above array we get the key 0 (which is not boolean false, see below). Then we can take that index and use it for the original array $secondArr and get the values from the other 2 columns.
-Note- that array search returns boolean false when it cant find the item, because PHP treats 0 and false the same we have to do a strict type check !== instead of just !=. Otherwise PHP will confuse the 0 index with being false, which is not something we want.
The second "trick" is use & in the foreach value, this is by reference which allows us to modify the array used in the loop, directly. This is optional as you could just as easily create a new array instead. But I thought I would show it as an option.

Making Terms Query in Elastic Search

I need to search multiple ids in the Elastic search. same like IN in SQL.
When I write static multiple IDs, it works but when I make IDs array and then implode to make comma-separated IDs for ES. It does not work.
Implode query:
$ids = array();
foreach ($this->session->userdata('cart') as $key => $value) {
$ids[] = trim($key);
}
$params = [
'index' => ES_INDEX_PD,
'body' => [
'query' => [
'constant_score' => [
'filter' => [
'terms' => [
'id' => [implode(",", $ids)]
]
],
]
]
]
];
$products = $this->elasticsearch->client->search($params);
This is from imploding result... Does not work
Array ( [index] => example-prod [body] => Array ( [query] => Array ( [constant_score] => Array ( [filter] => Array ( [terms] => Array ( [id] => Array ( [0] => 10241308,10928958 ) ) ) ) ) ) )
This is static IDs passed to query. This works
Array ( [index] => example-prod [body] => Array ( [query] => Array ( [constant_score] => Array ( [filter] => Array ( [terms] => Array ( [id] => Array ( [0] => 10241308 [1] => 10928958 ) ) ) ) ) ) )
No need to use extra implode() with , here when you pass ids. I had the same issue couple of months back.Just pass the array of ids like this to your terms query and it'll work perfectly.
$ids = array();
foreach ($this->session->userdata('cart') as $key => $value) {
$ids[] = trim($key);
}
$params = [
'index' => ES_INDEX_PD,
'body' => [
'query' => [
'constant_score' => [
'filter' => [
'terms' => [
'id' => $ids
]
],
]
]
]
];
$products = $this->elasticsearch->client->search($params);

How do I cast a string to an array

So as you can see below I have an array that I get from an ajax request.. Now is my question how can I use the [name] as an array? The arrays below are two different arrays
Changing the arrays below is done in PHP
So this:
(
[name] => template[options][4892][is_delete]
[value] => 1
)
(
[name] => template[options][4892][name]
[value] => just_a_name
)
Into this
(
[template] => (
[options] => (
[4892] => (
name => just_a_name,
is_delete => 1
)
)
)
)
Edited: changed value to is_delete
Edit2: changed some things to make it more clear
Hope this is clear enough
$data = [
[
'name' => 'template[options][4892][is_delete]',
'value' => 1
],
[
'name' => 'template[options][4892][name]',
'value' => 'name'
]
];
$parsedData = [];
foreach ($data as $item) {
parse_str($item['name'] . '=' . $item['value'], $out);
$parsedData = array_replace_recursive($parsedData, $out);
}
print_r($parsedData);
result:
Array(
[template] => Array(
[options] => Array(
[4892] => Array(
[is_delete] => 1
[name] => name
)
)
)
)

How to perform conditional delete in multidimensional array in PHP?

I need your help the problem description is given
The array is as follows
The given array is the sample. The main array contains many entries as follow where username can differ.
Case 1:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
1 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
Case 2:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
1 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
I want to delete the element where 'username'=>Pete and 'Option'=>no
So the output should be looks like
Array
(
[0] => Array
(
[username] => Pete
[userid] => 2
[option] => yes
)
[2] => Array
(
[username] => John
[userid] => 1
[option] => yes
)
)
All element of sub array can be same but option field either yes or no.
Please help me
Thank you very much in advance
this can be a solution
$result = array();
foreach ($yourArray as $key => $value) {
if(!($value['username']=="Pete" && $value['options']=="no"))
array_push($result, $value);
}
With this code you can achieve that:
foreach($my_array as $key => $value){
if($value['username'] == 'Pete' && $value['option'] == 'yes'){
unset($my_array[$key]);
}
}
Use a foreach loop! If the current value for username = pete add a variable user=true;
Then after that check if(option == no){ if(user==true){ DELETE ROW } }
You can use array_filter
>>> array_filter($my_array,
function($obj){
return $obj["option"] !== "no" || $obj["username"] !== "Pete";
}
)
=> [
1 => [
"username" => "Pete",
"userid" => 2,
"option" => "yes"
],
2 => [
"username" => "John",
"userid" => 1,
"option" => "no"
]
]
As the function name suggests, you should use array_filter()
$my_array = array_filter($my_array, function($v){
return ($v['username'] != 'Pete' && $v['option'] != 'no');
});

Which PHP Array function should I use?

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

Categories