Extend assoc array - php

I would like to extend an assoc array.
The original array is like
$arr = [[
'ID' => 0,
'TEXT' => SOME_CONST,
'CHECKED' => $opt_flag,
]];
With a new condition I would like to extend this existing array.
if (defined('MODULE_STATUS') && MODULE_STATUS == 'true') {
$arr['JSON_ATTRDATA'] = 1;
}
The result is
Array
(
[0] => Array
(
[ID] => 0
[TEXT] => text
[CHECKED] => 1
)
[JSON_ATTRDATA] => 1
)
What is wrong that the new key is outside of the nestet array?

you want $arr[0]['JSON_ATTRDATA'] = 1; right now you appending to the parent array, you want the child array which has the key 0

the Array $arr already having 1 object
to change this object value by its index
$arr[0] = "anything else"
and to add more objects
$arr[] = "Another object";
you should Call :
$arr[0]['JSON_ATTRDATA'] = 1;
will add another key => value to first object

Do $arr[0]['JSON_ATTRDATA']
DETAILS
$arr contains array within array. Like this
Array
(
[0] => Array
(
[ID] => 0
[TEXT] => text
[CHECKED] => 1
)
)
So when you add $arr['JSON_ATTRDATA'] it add into first array

Related

Getting array values sorted in new array, and then comparing with another Array

I have an array and want to get the values from it sorted and modified a bit to an other array, so I can make some comparison with yet another array
This is my array to begin with
Array (
[0] => WP_Term Object (
[term_id] => 10
...
[cat_name] => Klantenartikelen
[category_nicename] => klantenartikelen
[category_parent] => 0 )
[1] => WP_Term Object (
[term_id] => 11
...
[cat_name] => Overwin je Overgang blog
[category_nicename] => overwin-je-overgang-blog
[category_parent] => 10 )
)
I want to sort out the values of [cat_name] in to the new Array, remove one string from it ( blog) and then compare it with another Array, which looks like this
Array (
[1426787445] => Overwin je Overgang
[1426787487] => Overgangstransformatie
)
The problem with the second Array is that the key changes for every Array (membership secret code), but the values are always the same. (if it is too problematic to get the values from an Array like this, it can be hard-coded)
Then at the end I want to make a conditional logic with the comparison: if the value pairs of the two Array match, to echo a graphic element. There might be cases when one Array contains let's say 2 key/values pairs, and the other only 1, but it would need to pass true if one of the 2 is matching.
Any idea please, how this can be solved?
Given the following variables:
$data = Array (
(object) Array(
"term_id" => 10,
"cat_name" => "Klantenartikelen",
"category_nicename" => "klantenartikelen",
"category_parent" => 0
),
(object) Array(
"term_id" => 11,
"cat_name" => "Overwin je Overgang blog",
"category_nicename" => "overwin-je-overgang-blog",
"category_parent" => 10
)
);
$ref = Array (
1426787445 => "Overwin je Overgang",
1426787487 => "Overgangstransformatie"
);
You could then do this:
foreach ($data as $obj) {
// remove "blog"
$catname = str_replace(" blog", "", $obj->cat_name);
// find this name in the $ref array
$matchKey = array_search($catname, $ref);
if ($matchKey !== false) {
echo "Found '$catname' at key $matchKey", '<br>';
}
}
This produces this output:
Found 'Overwin je Overgang' at key 1426787445
At the place of the echo you could then output the image, etc...
Try this
$catname=$array_column($array, "cat_name");
$count=count($catname)
for($i=0; $i<$count; $i++){
foreach($anotherarray as $key => $value){
if($catname[$i]==$anotherarray[$key]){
echo "graphic";
}
}
}
find any error? post back

Put multiple arrays in one large associative array

I am creating a set of arrays with the following loop:
$assessmentArr = explode("&", $assessmentData);
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
//print_r($resultArr);
}
Which produces the following results:
Array
(
[0] => community-support
[1] => 24
)
Array
(
[0] => money-rewards
[1] => 30
)
Array
(
[0] => status-stability
[1] => 15
)
Array
(
[0] => personal-professional-development
[1] => 32
)
Array
(
[0] => community-support
[1] => 9
)
Array
(
[0] => money-rewards
[1] => 12
)
Array
(
[0] => status-stability
[1] => 16
)
Array
(
[0] => personal-professional-development
[1] => 29
)
I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.
So I would like the final output to be something like:
Array
(
[community-support] => 33
[money-rewards] => 42
[status-stability] => 31
[personal-professional-development] => 61
)
I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?
Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.
(Add this code in your loop):
if(!isset($result[$resultArr[0]]))
$result[$resultArr[0]] = $resultArr[1];
else
$result[$resultArr[0]] += $resultArr[1];
Then you have your desired array:
print_r($result);
You could do it like this
$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
if(array_key_exists($resultArr[1], $finalArr)){
$finalArr[$resultArr[0]] += $resultArr[1];
}else{
$finalArr[$resultArr[0]] = $resultArr[1];
}
}
First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.
... way too slow :/

php array merge with value of parent array

I need to merge an array with value of parent array.
$testArr=unserialize('a:6:{s:5:"queue";a:2:{i:6;s:1:"5";i:5;s:1:"2";}s:3:"sum";a:2:{i:6;s:3:"765";i:5;s:3:"2.1";}s:7:"sumAccD";a:2:{i:6;s:3:"543";i:5;s:3:"3.1";}s:7:"sumAccC";a:2:{i:6;s:2:"54";i:5;s:3:"3.3";}s:7:"comment";a:2:{i:6;s:12:"test comment";i:5;s:6:"111222";}s:3:"yt0";s:0:"";}');
$ret = array();
foreach ($testArr as $pkey => $pval) {
if (is_array($pval)) {
foreach ($pval as $pvkey => $pvval) {
$ret[$pvkey] = array($pkey => $pvval);
}
}
}
echo '<pre>', print_r($ret), '</pre>';
In this case it prints out
Array
(
[6] => Array
(
[comment] => test comment
)
[5] => Array
(
[comment] => 111222
)
)
1
Unfortunally it print out only comment. I need to add other rows: queue,sum,sumAccD,sumAccC. Array must look like this:
Array
(
[6] => Array
(
[queue] => 5
[sum] => ''
....
[comment] => test comment
)
[5] => Array
(
[queue] => 2
[sum] => 2.1
....
[comment] => 111222
)
)
1
Please help merge them.
Thanks.
Look at this line:
$ret[$pvkey] = array($pkey => $pvval);
You're assigning the key to a new array every time, overwriting what was previously there.
In your case, 'comment' is the last key that is processed, so that's going to be the only key in the final array.
Instead of this, you could define a new array only once outside the inner for, like this:
$ret[$pvkey] = array();
And then assign your values to that array in the inner for loop as you would normally do (so no more creating arrays there!)
Problem solved by replacing
$ret[$pvkey] = array($pkey => $pvval);
with
$ret[$pvkey][$pkey] = $pvval;

Most Efficient Way to Delete Nested Array Element

Say I have the following:
Array(
[0] => Array
(
[id] => 1
[item] => first item
)
[1] => Array
(
[id] => 3
[item] => second item
)
[2] => Array
(
[id] => 5
[item] => third item
)
)
I want to delete the item with id = 5. I know I can loop through the array and unset, but I'm hoping for a more direct/efficient solution.
If you cannot make the IDs the keys of the outer array (then you could simply use unset($arr[5]);), looping over the array is indeed the way to dg.
foreach($arr as $key => $value) {
if($value['id'] === 5) {
unset($arr[$key]);
break;
}
}
Another option would be using array_filter - that's less efficient though since it creates a new array:
$arr = array_filter($arr, function($value) {
return $value['id'] !== 5;
});
Why don't you create the array with the keys set as the ID's? E.g:
Array(
[1] => Array
(
[id] => 1
[item] => first item
)
[3] => Array
(
[id] => 3
[item] => second item
)
[5] => Array
(
[id] => 5
[item] => third item
)
)
You can then write:
<?php
unset($array[5]); // Delete ID5
?>
For Multi level nested array
<?php
function remove_array_by_key($key,$nestedArray){
foreach($nestedArray as $k=>$v){
if(is_array($v)){
remove_array_by_key($key,$v);
} elseif($k==$key){
unset($nesterArray[$k]);
}
}
return $nestedArrat;
}
?>
The most efficient way would be to have 2 arrays.
ID => Index
Index => Object (your current array)
Search for ID in your ID => Index helper array and the value will be the Index for your main array, then unset them both.

Removing a value from a PHP Array

Using PHP I'm trying to remove an element from an array based on the value of the element.
For example with the following array:
Array
(
[671] => Array
(
[0] => 1
[1] => 100
[2] => 1000
)
[900] => Array
(
[0] => 15
[1] => 88
}
)
I'd like to be able to specify a value of on of the inner arrays to remove. For example if I specified 100 the resulting array would look like:
Array
(
[671] => Array
(
[0] => 1
[2] => 1000
)
[900] => Array
(
[0] => 15
[1] => 88
}
)
My first thought was to loop through the array using foreach and unset the "offending" value when I found it, but that doesn't seem to reference the original array, just the loop variables that were created.
Thanks.
foreach($array as $id => $data){
foreach($data as $index => $offending_val){
if($offending_val === 100){
unset($array[$id][$index]);
}
}
}
You can use:
array_walk($your_array, function(&$sub, $key, $remove_value) {
$sub = array_diff($sub, array($remove_value));
}, 100);
Couple of ideas:
You could try array_filter, passing in a callback function that returns false if the value is the one you want to unset. Using your example above:
$new_inner_array = array_filter($inner_array, $callback_that_returns_false_if_value_100)
If you want to do something more elaborate, you could explore the ArrayIterator class of the SPL, specifically the offsetUnset() method.

Categories