comparing two arrays in PHP [closed] - php

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 8 years ago.
Improve this question
I have an array in PHP $array which has elements like
$array['id'].. $array['name'] $array['class']
I have another array called $array1 which has element only $array1['uid'].
I want to match these two array on the basis of $array['id'] and $array['uid']
such that I want to get elements $array['id'] not equal to $array['uid']`
Is there any builtin function in PHP, I can do that in for each loop with my custome function , but is there any function?
Input is if $array has id=2,4,5,6 and $array has uid=2,4 then I should get $array id=5,6
Data in $array looks like this
{
"name": "abc",
"id": "37402526"
},
{
"name": "def",
"id": "506768590"
},
{
"name": "hij",
"id": "526405977"
}
And $array 1 like this
{
"id": "37402526"
},
{
"id": "506768590"
},
{
"
"id": "526405977"
}

If you can rewrite your code, to have the id's in array keys, than you could use array_diff_key():
$array = array(
'12' => array('name' => 'abc'),
'34' => array('name' => 'def')
);
$array2 = array('12' => true);
$result = array_diff_key($array, $array2);
Otherwise you can use array_udiff():
function my_id_cmp($a, $b) {
return strcmp($a['id'], $b['id']);
}
$result = array_udiff($array, $array1, 'my_id_cmp');

If your input is just in the format you used as example, then it is simple :
$array['id'] = implode(',', array_diff(explode(',', $array['id']), explode(',', $array1['uid'])));
Regards.

Related

Use substr() in array without loop? [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 2 years ago.
Improve this question
Is there any way to use substr() function on all of an array's elements without using a loop?
Looping is sometimes the most simple and readable solution. But if you want to apply a function to every element of an array you can also use array_map.
Here an anonymous function is a simple wrapper for substr, which is used to return the first letter of each name in the given array:
<?php
$names =
[
'Gaga',
'Joplin',
'Vega'
];
$first_letters =
array_map(
function($str) { return substr($str, 0, 1); },
$names
);
var_export($first_letters);
Output:
array (
0 => 'G',
1 => 'J',
2 => 'V',
)
Short arrow functions introduced in Php 7.4. are slightly tidier:
array_map(
fn($str) => substr($str, 0, 1),
$names
);
The foreach/loop approach:
foreach($names as $key => $name)
$result[$key] = substr($name, 0, 1);
Mutating the original array:
foreach($names as &$name)
$name = substr($name, 0, 1);
unset($name);

PHP - Find an object by key in an array of objects, update its value

I have an array of objects, and want to update an attribute of one of the objects.
$objs = [
['value' => 2, 'key' => 'a'],
['value' => 3, 'key' => 'b'] ,
];
Let's say I want to set the 'value' of the object with 'key'=>'a' to 5.
Aside from iterating over the array searching for the key, is there any quicker/efficient way of doing this?
Thanks.
EDIT: There is debate as to why I can't use an associative array. It is because this array is obtained from a JSON value.
If my JSON object is this:
"obj": {
"a": {
"key": "a",
"value": 2
},
"b": {
"key": "b",
"value": 3
}
}
There is no guarantee that the order of the objects will be retained, which is required.
Hence I need an index in each object to be able to sort it using usort(). So my JSON needs to be:
"obj": {
"a": {
"key": "a",
"value": 2,
"index": 1
},
"b": {
"key": "b",
"value": 3,
"index": 2
}
}
But I cannot use usort() on an object, only on arrays. So my JSON needs to be
"obj": [
{
"key": "a",
"value": 2,
"index": 1
}, {
"key": "b",
"value": 3,
"index":2
}
]
Which brings us to the original question.
By using array_column(), you can pull all the values with the index key in the arrays. Then you can find the first occurrence of the value a by using array_search(). This will only return the first index where it finds a value. Then you can simply replace that value, as you now have the index of that value.
$keys = array_column($objs, 'key');
$index = array_search('a', $keys);
if ($index !== false) {
$objs[$index]['value'] = 5;
}
See this live demo.
http://php.net/array_search
http://php.net/array_column
You can make the array associative with array column. That way you can directly assign the value.
$objs = [ ['value'=>2, 'key'=>'a'], ['value'=>3, 'key'=>'b'] ];
$objs = array_column($objs, null, "key");
$objs['a']['value'] = 5;
https://3v4l.org/7tJl0
I want to recommend you reorginize your array lake that:
$objs = [
'a' => ['value'=>2, 'key'=>'a'],
'b' => ['value'=>3, 'key'=>'b']
];
And now
if( array_key_exists( 'a', $objs )) {
$objs ['a'] ['value'] = 5;
}
I had it like that initially. But I need for the objects to have an
index value in them, so I can run usort() on the main array. This is
because the array comes from JSON where the original order isn't
respected
Then create an index array:
// When fill `$objs` array
$objs = [];
$arrIndex = [];
$idx = 0;
foreach( $json as $item ) {
$arrIndex [ $item ['key']] = $idx;
$objs [$idx ++] = $item;
}
// And your task:
if( array_key_exists( 'a', $arrIndex )) {
$objs [ $arrIndex ['a']] ['value'] = 5;
}
Aside from iterating over the array searching for the key, is there
any quicker/efficient way of doing this?
You have to pay the price of iteration either way.
You can search your collection for the interesting object (takes linear time), or you form some kind of dictionary data structure, e.g. hash table (takes linear time) and then find the interesting object in constant time.
No free lunches here.

PHP: Getting values by date [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 4 years ago.
Improve this question
Im new In PHP!.
I have an array that contains dates and vlaues. How do i get all values of
specific date?. EXp: I would like to get all values from year 2015. If someone Knows can guide me.
You could use array_filter, then check the array key substr matches the date.
<?php
$date = 2016;
$array = [
'2016-01-01' => 'a',
'2016-01-02' => 'b',
'2016-12-01' => 'c',
'2017-01-04' => 'd',
'2017-01-05' => 'e',
'2017-01-06' => 'f',
];
$result = array_filter($array, function ($key) use ($date) {
return substr($key, 0, strlen($date)) == $date;
}, ARRAY_FILTER_USE_KEY);
print_r($result);
https://3v4l.org/UYaQq
Result:
Array
(
[2016-01-01] => a
[2016-01-02] => b
[2016-12-01] => c
)
<?php
$array = array('2015-01-01' => "test1",
'2013-02-04' => "test2",
'2011-03-08' => "test3",
'2016-03-08' => "test3");
foreach( $array as $key => $value ){
if(date('Y',strtotime($key)) >= 2015)
echo $value . ", ";
}
?>
An Array Contains a Key and a Value. The Key in your case is the Date. And the Value is... the value
You define it like this
$array = array(
Date => Value,
AnotherDate => AnotherValue,
);
or since PHP5
$array = [
Date => Value,
AnotherDate => AnotherValue,
];
if you now look at your Array using
var_dump($array);
You'll see the date is already combined with your value and It will even show the type of value (boolean, string, integer...)
Edit
Anotherone was faster

Confusion in conversion of array to json in php [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
I have an array $arr_name which prints out
{"name" => "tom", "age" => 10}, {"name" => "jack", "age" => 11}
how do i get it to print the desired output using php ?
Desired Output in JSON is as follows
{
"Students" : [ {"name" => "tom", "age" => 10}, {"name" => "jack", "age" => 11}
]
}
Sorry but i find this very very confusing and have spent the last 2 hrs trying to get "Students" key asssigned to have a value with the contents of $arr_name
PHP already has a built in function to convert an array into JSON:
json_encode
Here simple example given below like:
Put your array place of $put_your_array in loop:
$output=array();
foreach ($put_your_array as $key => $value) {
$output['Students'][]=array(
'name'=>$value['name'],
'age'=>$value['age']
);
}
echo json_encode($output);
And get output would you seem like json format...
the easiest way to do that, loop through the array then assign it to new array
Ex:
$new_array=array();
foreach(your array as $key => $val)
{
$new_array['Students'][] = $val;
}
return json_encode($new_array);

Create Multi Array Json File in 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 6 years ago.
Improve this question
In My Web Application I am Using Json. I Need to create following Format of Json File in PHP.
{
"title": "A cool blog post",
"clicks": 4000,
"children": null,
"published": true,
"comments": [
{
"author": "Mister X",
"message": "A really cool posting"
},
{
"author": "Misrer Y",
"message": "It's me again!"
}
]
}
Here is the solution:
Open Google
Type PHP JSON
hit Enter
Click the 1st result
Replace the values from PHP examples with json_encode with your own values
json_encode will encode a PHP array as a JSON array.
As the exmaple on that link shows:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
// {"a":1,"b":2,"c":3,"d":4,"e":5}

Categories