Removing unwanted key/value pair in php array? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
above is my output but i want an array like below format. Please help me.
Correct Output:
$data = array ("id"=>"1","name"=>"mani","lname"=>"ssss");

check this, use is is_numeric to check number or string.
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
foreach ($data as $key => $val)
{
if(!is_numeric($key))
{
$new_array[$key] = $val;
}
}
print_r($new_array);
OUTPUT :
Array
(
[id] => 1
[name] => mani
[lname] => ssss
)
DEMO

The Code-Snippet below contains Self-Explanatory Comments. It might be of help:
<?php
// SEEMS LIKE YOU WANT TO REMOVE ITEMS WITH NUMERIC INDEXES...
$data = array( "0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname"=> "ssss"
);
// SO WE CREATE 2 VARIABLES TO HOLD THE RANGE OF INTEGERS
// TO BE USED TO GENERATE A RANGE OF ARRAY OF NUMBERS
$startNum = 0; //<== START-NUMBER FOR OUR RANGE FUNCTION
$endNum = 10; //<== END-NUMBER FOR OUR RANGE FUNCTION
// GENERATE THE RANGE AND ASSIGN IT TO A VARIABLE
$arrNum = range($startNum, $endNum);
// CREATE A NEW ARRAY TO HOLD THE WANTED ARRAY ITEMS
$newData = array();
// LOOP THROUGH THE ARRAY... CHECK WITH EACH ITERATION
// IF THE KEY IS NUMERIC... (COMPARING IT WITH OUR RANGE-GENERATED ARRAY)
foreach($data as $key=>$value){
if(!array_key_exists($key, $arrNum)){
// IF THE KEY IS NOT SOMEHOW PSEUDO-NUMERIC,
// PUSH IT TO THE ARRAY OF WANTED ITEMS... $newData
$newData[$key] = $value;
}
}
// TRY DUMPING THE NEWLY CREATED ARRAY:
var_dump($newData);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
Or even concisely, you may walk the Array like so:
<?php
$data = array(
"0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname" => "ssss"
);
array_walk($data, function($value, $index) use(&$data) {
if(is_numeric($index)){
unset($data[$index]);
}
});
var_dump($data);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)

$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
$new_data = array();
foreach($data as $k => $v)
if(strlen($k)>1) $new_data[$k] = $v;
print_r($new_data);

I'm a little confused as to what exactly you're looking for. You give examples of output, but they look like code. If you want your output to look like code you're going to need to be clearer.
Looking at tutorials and documentation will do you alot of good in the long run. PHP.net is a great resource and the array documentation should help you out alot with this: http://php.net/manual/en/function.array.php

Related

PHP: can't add to empty associative array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i'm missing something simple here trying to add a new key/value pair and then add to the value of that pair as this loop goes on. this throws an undefined index error:
$someAssocArray = [2] => 'flarn'
[3] => 'turlb'
$someOtherAssocArray = [0] => 'id' => '11'
'name' => 'flarn'
[1] => 'id' => '22'
'name' => 'turlb'
[2] => 'id' => '33'
'name' => 'turlb'
[3] => 'id' => '44'
'name' => 'flarn'
$idList = [];
foreach($someAssocArray as $key=>$value) {
foreach($someOtherAssocArray as $item) {
if($item['name'] === $value) {
$idList[$value] += $item['id'];
}
}
}
the end result of idList should look like this:
$idList = [ "flarn" => "11,44"
"turlb" => "22,33" ]
so please tell me what i'm missing so i can facepalm and move on.
[Edit] OK I just re-read that question and I might be misunderstanding. Is the desired output of 11,44 supposed to represent the sum of the values? Or a list of them?
This code will generate a warning if $idList[$value] doesn't exist:
$idList[$value] += $item['id'];
This is happening because it has no value yet for the first time you're incrementing. You can avoid this issue by initializing the value to zero for that first time when it doesn't exist:
If you want a sum of the values:
if($item['name'] === $value) {
$idList[$value] ??= 0; // initialize to zero
$idList[$value] += $item['id']; // add each value to the previous
}
If you want a list of the values:
if($item['name'] === $value) {
$idList[$value] ??= []; // initialize to an empty array
$idList[$value][] = $item['id']; // append each element to the list
}
(Then you can use implode() to output a comma-separated string if desired.)

Remove dynamic array of keys from multidimensional array [duplicate]

This question already has answers here:
Unset inside array_walk_recursive not working
(3 answers)
Closed 2 years ago.
I've looked through articles and SO questions for the last hour and still can't find exactly what I'm looking for.
I have a single dimensional string array containing containing keys from my multidimensional array. Both arrays are dynamic. I need a way to remove every key in the 1D from the MD array.
It's hard to explain, so let me just show you.
$dynamicKeys = ['date', 'name', 'account'];
$arrayRequiringSanitization = [
'name' => [
'first' => 'Homer',
'last' => 'simpson'
],
'age' => 'unknown',
'facts' => [
'history' => [
'date' => 'whenever',
'occurred' => 'nope'
],
'is' => 'existing'
]
];
function removeDynamicValues($arr, $vals) {
// this is where i need help
}
The removeDynamicValues function should take the $arrayRequiringSanitization and $dynamicKeys and return an array that looks as follows:
$arrayRequiringSanitization = [
'age' => 'unknown',
'facts' => [
'history' => [
'occurred' => 'nope'
],
'is' => 'existing'
]
];
So basically, it removed the name sub array and the date sub sub property. The important part is that both arrays are dynamic, and it's not known how deep $arrayRequiringSanitization will be nested.
Let me know if I need to provide further clarrification.
You can do this quite easily with recursion. Here's the code.
/**
* #param array<mixed> $arr initial array
* #param array<string|int> $vals array of keys that need to be deleted
* #return array<mixed>
*/
function removeDynamicValues(array $arr, array $vals): array
{
$out = [];
foreach ($arr as $key => $value) {
if (!in_array($key, $vals, true)) {
$out[$key] = is_array($value) ? removeDynamicValues($value, $vals) : $value;
}
}
return $out;
}

Split multidimensional array into arrays

So I have a result from a form post that looks like this:
$data = [
'id_1' => [
'0' => 1,
'1' => 2
],
'id_2' => [
'0' => 3,
'1' => 4
],
'id_3' => [
'0' => 5,
'1' => 6
]
];
What I want to achieve is to split this array into two different arrays like this:
$item_1 = [
'id_1' => 1,
'id_2' => 3,
'id_3' => 5
]
$item_2 = [
'id_1' => 2,
'id_2' => 4,
'id_3' => 6
]
I've tried using all of the proper array methods such as array_chunk, array_merge with loops but I can't seem to get my mind wrapped around how to achieve this. I've seen a lot of similar posts where the first keys doesn't have names like my array does (id_1, id_2, id_3). But in my case the names of the keys are crucial since they need to be set as the names of the keys in the individual arrays.
Much shorter than this will be hard to find:
$item1 = array_map('reset', $data);
$item2 = array_map('end', $data);
Explanation
array_map expects a callback function as its first argument. In the first line this is reset, so reset will be called on every element of $data, effectively taking the first element values of the sub arrays. array_map combines these results in a new array, keeping the original keys.
The second line does the same, but with the function end, which effectively grabs the last element's values of the sub-arrays.
The fact that both reset and end move the internal array pointer, is of no concern. The only thing that matters here is that they also return the value of the element where they put that pointer to.
Solution without loop and just for fun:
$result = [[], []];
$keys = array_keys($data);
array_map(function($item) use(&$result, &$keys) {
$key = array_shift($keys);
$result[0][$key] = $item[0];
$result[1][$key] = $item[1];
}, $data);
Just a normal foreach loop will do.
$item_1 = [];
$item_2 = [];
foreach ($data as $k => $v){
$item_1[$k] = $v[0];
$item_2[$k] = $v[1];
}
Hope this helps.

How to define a custom key in PHP arrays? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to define a two dimension array like below:
[40.1][John]
[40.2][Jane]
[40.7][Mary]
[40.10][Sara]
in other words I want to define an array with custom key. Later I need to access to the array values with the custom key. for instance :
echo(myarray[40.2]);
And I need to generate the array dynamically from XML , since the values are coming from a XML file.
The XML file which I want to generate the array from is like below:
<rules>
<rule>
<id>40.1</id>
<regex><![CDATA[/(?:\)\s*when\s*\d+\s*then)/]]></regex>
</rule>
<rule>
<id>40.2</id>
<regex><![CDATA[/(?:"\s*(?:#|--|{))/]]></regex>
</rule>
How should I create the array with above characteristics?
You can do this very easily by creating an associative array
$myarray = array(
"40.1" => "John",
"40.2" => "Jane",
"40.7" => "Mary",
"40.10" => "Sara"
);
Later on you can iterate over this array with a foreach loop
foreach($myarray as $key => $value) {
echo "<p>" . $key . " = " . $value . "</p>";
}
This will output to the screen
40.1 = John
40.2 = Jane
40.7 = Mary
40.10 = Sara
To create a new array and add items to is as easy as doing this
$myarray = array();
$myarray[$newkey] = $newvalue;
For a two dimensional array, you can define them like this
$myarray = array();
$myarray[$key] = array();
$myarray[$key]['John'] = 'some value';
$myarray[$key]['Jane'] = 'another value';
$myarray[$key2] = array();
$myarray[$key2]['Mary']= 'yet another value';
Or as a short cut
$myarray = array(
$key => array(
'John' => 'some value',
'Jane' => 'another value',
),
$key2 = array(
'Mary' => 'yet another value'
)
);
You can do it with associative array key => value.
$arr = array('40.1' => 'John', '40.2' => 'Jane', '40.7' => 'Mary', ...);
echo $arr['40.1']; // will return John
If you think to extend the data in the feature, you can do it with nested arrays
$arr = array(
'40.1' => array('name' => 'John', 'eyes' => 'green');
'40.2' => array('name' => 'Jane', 'eyes' => 'blue');
);
You can access nested array like this:
echo $arr['40.2']['eyes'] // return blue
You can see also PHP documentation about arrays here
Array keys
Notice! Do not use "float" as type for array keys.
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
Output will be:
array(1) {
[1]=>
string(1) "d"
}
Taken from http://www.php.net/manual/en/language.types.array.php.
Two-dimensional arrays
You can create your array like this:
$data = [
'40.2' => [
'John' => [
// and now this is second dimension
]
]
];
Add aditional stuff:
$data['40.2']['John'][] = ; // just append value
// or
$data['40.2']['John']['sex'] = 'Male'; // store it with key
Or if you need to store scalar values, you can define array like this:
$data = [
'40.2' => [
'John' => 'male' // storing scalar values
]
];
Sorry, If I misunderstood your question.

How do i push a new key value pair to an array php? [duplicate]

This question already has answers here:
How to push both value and key into PHP array
(21 answers)
Closed 10 months ago.
I know there is a lot of documentation around this but this one line of code took me ages to find in a 4000 line file, and I would like to get it right the first try.
file_put_contents($myFile,serialize(array($email_number,$email_address))) or die("can't open file");
if ($address != "email#domain.com") {
$email['headers'] = array('CC' => 'email#domain.com');
}
}
After this if statement I basically want to add on
'BCC' => 'another_email#domain.com'
into the $email['headers'] array (so it adds it whether the if evaluates to true or not)
You can add them individually like this:
$array["key"] = "value";
Collectively, like this:
$array = array(
"key" => "value",
"key2" => "value2"
);
Or you could merge two or more arrays with array_merge:
$array = array( "Foo" => "Bar", "Fiz" => "Buz" );
$new = array_merge( $array, array( "Stack" => "Overflow" ) );
print_r( $new );
Which results in the news key/value pairs being added in with the old:
Array
(
[Foo] => Bar
[Fiz] => Buz
[Stack] => Overflow
)
You can do this: $email['headers']['BCC'] = "Test#rest.com"
but you need to add it after the if.
$email['headers'] = array();
if ($address != "email#domain.com") {
$email['headers']['CC'] = 'email#domain.com';
}
$email['headers']['BCC'] = 'another_email#domain.com';

Categories