iOS: adding key/value to multidimentional array at specific index - ios

I'm pretty new in iOS dev. Basically I have a multidimensional array as per below
Array
(
[0] => Array
(
[Name] => Peter
[Gender] => Male
)
[1] => Array
(
[Name] => Glenn
[Gender] => Female
)
[2] => Array
(
[Name] => Richard
[Gender] => Male
)
)
At some point, I am going to add in additional key/value at certain index. Take for example, I am adding a new entry at index 1 at the end of the array(the sequence is not something to bother actually, it can fit in front or at the end) with [Location] => Japan
As such, the array should looks like this:
Array
(
[0] => Array
(
[Name] => Peter
[Gender] => Male
)
[1] => Array
(
[Name] => Glenn
[Gender] => Female
[Location] => Japan
)
[2] => Array
(
[Name] => Richard
[Gender] => Male
)
)
How can I achieve that? Pls inspect my code below as I really have no idea as every attempt results in EXC_BAD_ACCESS or app being terminated. Thanks in advance, Jason.
for(int x=0; x<[arrayVisitor count]; x++)
{
if ([[[arrayVisitor objectAtIndex:x]objectForKey:(#"Gender")]isEqual:#"Female"])
[[arrayVisitor objectAtIndex:x] addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: #"Location",#"Japan",nil]];
}

For this type of adding key value pair to array you need to use NSMutableArray and NSMutableDictionary.
NSMutableArray *outerArray=[[NSMutableArray alloc] init];
NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc]initWithDictionary:[outerArray objectAtIndex:1]];
[mutableDict setObject:#"Japan" forKey:#"Location"];
[outerArray replaceObjectAtIndex:1 withObject:mutableDict];
Or using for loop as:------------------
NSMutableArray *arrayVisitor=[[NSMutableArray alloc] init];
int arrayLength=arrayVisitor.count;
for (int i=0;i<arrayLength;i++) {
NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc]initWithDictionary:[arrayVisitor objectAtIndex:i]];
if ([[mutableDict valueForKey:#"Gender"] isEqualToString:#"Female"]) {
[mutableDict setObject:#"Japan" forKey:#"Location"];
[arrayVisitor replaceObjectAtIndex:i withObject:mutableDict];
}
}
Note:- It is not multidimensional array , it is Array of NSDictionary objects,It should look like this
Array=(
{
Name= Peter
Gender= Male
},
{
Name = Glenn
Gender = Female
},
{
Name = Richard
Gender = Male
}
)

Related

unset not deleting key in multidimensional array

I have multidimensional array and wants to remove delivery location where ever it exists
Array
(
[0] => Array
(
[amountReceived] => 1
[deliveryLocation] => germany
)
[1] => Array
(
[amountReceived] => 2
[deliveryLocation] => bulgaria
)
)
PHP
foreach ($arr as $val)
{
foreach($val as $k => $v)
{
if($k == 'deliveryLocation')
{
unset($arr[$k]);
}
}
}
return $arr;
problem is it's returning above array as it is without removing any key from it.
Easy and fast to understand way
$t=0;
foreach ($arr as $val)
{
unset($arr[$temp]['deliveryLocation']);
$t++;
}

Index in foreach starts not with 0

$rounds = $season->championsLeague->rounds->where('stage', 'Olympic')->take(2);
$indexes = [];
foreach ($rounds as $index => $round) {
$indexes[] = $index;
}
echo '<pre>';print_r($indexes);echo '<pre>';
And I receive in indexes: Array
(
[0] => 6
[1] => 7
)
How it is possible?
Why not Array
(
[0] => 0
[1] => 1
)
The slice, chunk, and reverse methods now preserve keys on the collection. If you do not want these methods to preserve keys, use the values method on the Collection instance. This is from laravel documentation. I think it is true for take method also.

AFNetworking - Request format is not proper when using dictionaries

I'm sending a dictionary 'childDetails' which has a dictionary (rewards) as one of its objects.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:url parameters:childDetails constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
This "rewards" dictionary has two keys "name" and "value" which looks like {#"name",#"Reward 1",#"value",#"10"}.
when this gets posted to the server, the server receives it as follows;
Array
(
[group_id] => 5
[name] => John Doe
[rewards] => Array
(
[0] => Array
(
[name] => Sample reward 2
)
[1] => Array
(
[value] => 50
)
[2] => Array
(
[name] => Sample Reward 1
)
[3] => Array
(
[value] => 10
)
)
[tasks] => Array
(
[0] => Array
(
[title] => Default task one
)
[1] => Array
(
[title] => Default task two
)
[2] => Array
(
[title] => Default task five
)
)
[token] => 5332884c2bc8c5
)
Any Idea how to fix this?
Any help is much appreciated.
Thanks in advance
I think the "parameters: param of POST: only accepts key/value pairs. Are you sure you don't have to serialize manually your objects first ?
Can you print the content of "childDetails" please ?
I found out that inorder to get it to work, you have to reformat your dictionary.
In my case I had to change it as;
NSDictionary *parameters = #{
#"rewards": #[
{#"reward name",#"reward value"},
{#"reward name",#"reward value"}
]
};;

Neo4j ResultSet Object - how to get data if result is an array

I have one gremlin query in which I used cap().next()
and Everyman\Neo4j\Query\ResultSet Object is
...
[data:protected] => Array
(
[v[1079]] => Array
(
[0] => 14
)
[v[1082]] => Array
(
[0] => 25
)
[v[1016]] => Array
(
[0] => 5
)
[v[1078]] => Array
(
[0] => 10
)
[v[1081]] => Array
(
[0] => 17
)
)
...
how to get that array?
$result[0][0] is not working.
To iterate ResultSets use
foreach ($result as $row) {
echo $row['x']->getProperty('your_property') . "\n";
}
or with scalar values in column y
foreach ($result as $row) {
echo $row['x']->getProperty('your_property') . ": " . $row['y'] ."\n";
}
It would be nice to have the original gremlin query thought to see what you are returning from it.
see github

Intersect array of hashes with array of ids

I have an array of hashes, this is not an active record model. This array is of objects of type Person with properties of id, name, age. I have a second array of strings, ["john", "james", "bill"].
I am attempting to remove all objects in the array of hashes except for the ones who have names in the second array, essentially performing an intersect, but I'm having quite a few problems. Any suggestions? I'm not sure if my syntax is just off or if I'm thinking about this the wrong way. Obviously I can just iterate through but this seems like its probably not the best way to handle the situation.
http://www.ruby-doc.org/core-1.9.2/Array.html#method-i-select
arr1 = [{:id => 1, :name => "John"}, {:id => 2, :name => "Doe"}];
arr2 = ["Doe"];
intersect = arr1.select {|o| arr2.include? o[:name]} # you can also use select!
p intersect # outputs [{:name=>"Doe", :id=>2}]
Late to the party, but if arr1 :name is an array this works nicely:
arr1 = [{:id => 1, :name => ["John", "Doe"]}, {:id => 2, :name => ["Doe"]}];
arr2 = ["Doe"]
> intersect = arr1.reject{|o| (arr2 & o[:name]).empty?}
=> [{:id=>1, :name=>["John", "Doe"]}, {:id=>2, :name=>["Doe"]}] #output
> arr2 = ["John"]
> intersect = arr1.reject{|o| (arr2 & o[:name]).empty?}
=> [{:id=>1, :name=>["John", "Doe"]}] #output
or use select:
intersect = arr1.select{|o| !(arr2 & o[:name]).empty?}
To remove all objects in the array of hashes except for the ones who have names in the second array, you can do:
arr1.reject!{|o| (arr2 & o[:name]).empty?}

Resources