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

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.)

Related

Deleting elements from an array in PHP having more than 1 value in common [closed]

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 2 years ago.
Improve this question
I have a PHP array $element like this below with a list of words followed by a number
car 1
house 1
boat 1
book 3
question 2
about 2
draft 2
bounce 7
tag 5
dog 5
How can I remove from this array all the words having more than one number in common ?
I need this as result
book 3
bounce 7
I am assuming your array is :
$myArray = [
'car' => 1,
'house' => 1,
'boat' =>1,
'book' => 3,
'question' => 2,
'about' => 2,
'draft' => 2,
'bounce' => 7,
'tag' => 5,
'dog' => 5
];
You can remove duplicate values in this way :
Loop through the array, and store the value in a variable. I am storing it in a $lastValue variable.
in the loop check if the new value is equal to the last one, if true then start the loop again and find all the values of array equal to the last value and remove them using unset().
$lastValue = '';
//key is cat, house, boat ...
//value is key value 1,1,1,3...
foreach($myArray as $key => $value){
if($value == $lastValue){
foreach($myArray as $key2 => $value2){
if($value2 == $lastValue){
unset($myArray[$key2]);
}
}
}
$lastValue = $value;
}
print_r($myArray);
You can loop through the array and store the values in an associative array using the number as the key and whatever you want as a final result as the value.
While looping you might encounter keys that already exist. In this case you need to track the key to prevent it from being added again in another array and remove the value from the associative array.
In the end, only those elements that do not have duplicate keys, will be in the associative array.
Can look like this:
<?php
$values = [
['car', 1],
['house', 1],
['boat', 1],
['book', 3],
['question', 2],
['about', 2],
['draft', 2],
['bounce', 7],
['tag', 5],
['dog', 5],
];
$result = [];
$duplicateIndex = [];
foreach($values as $value) {
if(in_array($value[1], $duplicateIndex)) {
continue;
}
if(isset($result[$value[1]])) {
$duplicateIndex[] = $value[1];
unset($result[$value[1]]);
} else {
$result[$value[1]] = $value;
}
}
var_dump(array_values($result));
There are several other options as well. One would be to loop twice. Count how often a key occurs in the first run and add those with one occurrence to a result array in the second loop.

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

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

How Can I Read this Array Code? using PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have one code, I cannot imagine, how can I read this array, using php. please help me to..
array(
'serialize_data' => array(
array('name' => 'cadidate_id_0', value => '81112890V'),
array('name' => 'cadidate_id_1', value => '822312890V'),
array('name' => 'cadidate_id_2', value => '873312110V'),
array('name' => 'cadidate_id_3', value => '873312890V')
)
);
foreach($array as $key=>$value){
echo $value[0]['name'];
echo $value[0]['value'];
}
use above line to print your array element, like index number 0.
Have you tried
print_r($your-array);
?
To access individual levels it looks like you need to go down a level or two. I.e.
echo $your-array['serialize_data'][0]['name'];
you can use following method.
$array = array(
'serialize_data' => array(
array('name' => 'cadidate_id_0', value => '81112890V'),
array('name' => 'cadidate_id_1', value => '822312890V'),
array('name' => 'cadidate_id_2', value => '873312110V'),
array('name' => 'cadidate_id_3', value => '873312890V')
)
);
foreach($array as $key=>$value){
echo '<pre>'; print_r($value); echo '</pre>';
}
using this method you can read or access its name and value by passing the index number.
like:
echo '<pre>'; print_r($value[0]); echo '</pre>';
try
//grab array of name and value
$array=$data-array['serialize_data']
//traverse
foreach($nv as $array)
{
$name=$nv['name'];
$value=$nv['value'];
//do something to name
print $name;
//do something to value
print $value;
}

PHP Array needs fixed (consolidated/merged)

I have this multidimensional array which I'll name "original":
$original=
array
0 =>
array
'animal' => 'cats'
'quantity' => 1
1 =>
array
'animal' => 'dogs'
'quantity' => '1'
2 =>
array
'animal' => 'cats'
'quantity' => '3'
However, I want to merge internal arrays with the same animal to produce this new array (with quantities combined):
$new=
array
0 =>
array
'animal' => 'cats'
'quantity' => 4
1 =>
array
'animal' => 'dogs'
'quantity' => '1'
I understand that there are similar questions on stackoverflow, but not similar enough for me to be able to figure out how to use the feedback those questions have gotted to apply to this specific example. Yes, I know I probably look stupid to a lot of you, but please remember that there was a time when you too didn't know crap about working with arrays :)
I've tried the following code, but get Fatal error: Unsupported operand types (Referring to line 11). And if I got that error to go away, I'm not sure if this code would even produce what I'm trying to achieve.
$new = array();
foreach($original as $entity){
if(!isset($new[$entity["animal"]])){
$new[$entity["animal"]] = array(
"animal" => $entity["animal"],
"quantity" => 0,
);
}
$new[$entity["animal"]] += $entity["quantity"];
}
So, I don't know what I'm doing and I could really use some help from the experts.
To try to give a super clear question, here goes... What changes do I need to make to the code so that it will take $original and turn it into $new? If the code I provided is totally wrong, could you provide an alternative example that would do the trick? Also, the only language I am familiar with is PHP, so please provide an example using only PHP.
Thank you
You're very close.
$new[$entity["animal"]] += $entity["quantity"];
needs to be
$new[$entity["animal"]]['quantity'] += $entity["quantity"];
In your if ( !isset [...] ) line, you're setting $new[$entity['animal']] to an array, so you need to access the 'quantity' field of that array before trying to add the new quantity value to it.
One of the reasons why your code is not working is that you're using the animal name as the array index, not the integer index which is used in your desired output.
Try this:
$new = array(); // Desired output
$map = array(); // Map animal names to index in $new
$idx = 0; // What is the next index we can use
foreach ($original as $entity) {
$animal = $entity['animal'];
// If we haven't saved the animal yet, put it in the $map and $new array
if(!isset($map[$animal])) {
$map[$animal] = $idx++;
$new[$map[$animal]] = $entity;
}
else {
$new[$map[$animal]]['quantity'] += $entity['quantity'];
}
}
This works:
$new = array();
$seen = array();
foreach($original as $entity) {
// If this is the first time we're encountering the animal
if (!in_array($entity['animal'], $seen)) {
$new[] = $entity;
$seen[] = $entity['animal'];
// Otherwise, if this animal is already in the new array...
} else {
// Find the index of the animal in the new array...
foreach($new as $index => $new_entity) {
if ($new_entity['animal'] == $entity['animal']) {
// Add to the quantity
$new[$index]['quantity'] += $entity['quantity'];
}
}
}
}
Your example was using the animal name as the index, yet the actual index is just an integer.
However, I think the resulting array would be easier to use and easier to read if it was formatting like this instead:
array('cats' => 4, 'dogs' => 1)
That would require different but simpler code than above... but, it wouldn't be a direct response to your question.

Incorrect PHP sizeof or count [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
The following is a print_r of an array converted from an XML document:
Array
(
[layer1] => Array
(
[item] => Array
(
[item-id] => 1886731
[item-name] => Bad Dog
[category] => pets
[link] = http://www.baddog.com/
)
[total-matched] => 1
)
)
For the above array, sizeof($myarray[layer1][item]) should return 1, but it returns 4. I get the correct number of "item" items if there are more than one of them. The same error happens regardless of whether I use "sizeof" or "count". How do I get PHP to return "1" when there is only one item?
Consequently, if there is one item, I can't access item-name using array[layer1][item][0][item-name], I have to use array[layer1][item][item-name].
There is a world of difference between:
$array1 = array(
'layer1' => array(
'item' => array(
'0' => array(
'item-id' => 123123,
'item-name' => 'Bad Dog',
'category' => 'pets',
'link' => 'http://www.baddog.com/',
),
)
)
);
and:
$array2 = array(
'layer1' => array(
'item' => array(
'item-id' => 123123,
'item-name' => 'Bad Dog',
'category' => 'pets',
'link' => 'http://www.baddog.com/',
)
)
);
Basically they are different structures, and PHP is correct to return the following:
count($array1['layer1']['item']);
/// = 1 (count of items in the array at that point)
count($array2['layer1']['item']);
/// = 4 (count of items in the array at that point)
If you wish to get a count for ['layer1']['item'] that makes sense to your app, you will always need ['layer1']['item'] to be an array containing multiple array structures... i.e. like $array1 above. This is the reason why I ask what is generating your array structure because - whatever it is - it is basically intelligently stacking your array data depending on the number of items, which is something you don't want.
Code that can cause an array to stack in this manner normally looks similar to the following:
/// $array = array(); /// this is implied (should be set elsewhere)
$key = 'test';
$newval = 'value';
/// if we are an array, add a new item to the array
if ( is_array($array[$key]) ) {
$array[$key][] = $newval;
}
/// if we have a previous non-array value, convert to an array
/// containing the previous and new value
else if ( isset($array[$key]) ) {
$array[$key] = array($array[$key],$newval);
}
/// if nothing is set, set the $newval
else {
$array[$key] = $newval;
}
Basically if you keep calling the above code, and tracing after each run, you will see the following structure build up:
$array == 'value';
then
$array == array(0 => 'value', 1 => 'value');
then
$array == array(0 => 'value', 1 => 'value', 2 => 'value');
It's the first step in this process that is causing the problem, the $array = 'value'; bit. If you modify the code slightly you can get rid of this:
/// $array = array(); /// this is implied (should be set elsewhere)
$key = 'test';
$newval = 'value';
/// if we are an array, add a new item to the array
if ( is_array($array[$key]) ) {
$array[$key][] = $newval;
}
/// if nothing is set, set the $newval as part of an subarray
else {
$array[$key] = array($newval);
}
As you can see all I've done is delete the itermediate if statement, and made sure when we discover no initial value is set, that we always create an array. The above will create a structure you can always count and know the number of items you pushed on to the array.
$array == array(0 => 'value');
then
$array == array(0 => 'value', 1 => 'value');
then
$array == array(0 => 'value', 1 => 'value', 2 => 'value');
update
Ah, I thought so. So the array is generated from XML. In this case I gather you are using a predefined library to do this so modifying the code is out of the question. So as others have already stated, your best bet is to use one of the many XML parsing libraries available to PHP:
http://www.uk.php.net/simplexml
http://www.uk.php.net/dom
When using these systems you retain more of an object structure which should be easier to count. Both the above also support xpath notation which can allow you to count items without even having to grab hold of any of the data.
update 2
Out of the function you've given, this is the part that is causing your arrays to stack in the manner that is causing the problem:
$children = array();
$first = true;
foreach($xml->children() as $elementName => $child){
$value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
if(isset($children[$elementName])){
if(is_array($children[$elementName])){
if($first){
$temp = $children[$elementName];
unset($children[$elementName]);
$children[$elementName][] = $temp;
$first=false;
}
$children[$elementName][] = $value;
}else{
$children[$elementName] = array($children[$elementName],$value);
}
}
else{
$children[$elementName] = $value;
}
}
The modification would be:
$children = array();
foreach($xml->children() as $elementName => $child){
$value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
if(isset($children[$elementName])){
if(is_array($children[$elementName])){
$children[$elementName][] = $value;
}
}
else{
$children[$elementName] = array($value);
}
}
That should stop your arrays from stacking... however if you have any other part of your code that was relying on the previous structure, this change may break that code.

Categories