PHP: Modify an associative array based on value of a key - php

I have an array like this
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 3
[type] => default
[place] => 2
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
This array is created from this php
for($count=1;$count <= 3;$count++){
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
Now I want to change the result of this array if the place is found by the php mysql data. For example I have this array.
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
As you can see that the second array is in "place 2". Now I want the result be like this
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
How to achieve this? I have already done with array_search function but no luck.
anyone please help me
=======================EDIT FULL CODE================================
Here is the code, I'm showing the data from database and call it in while loop function
for($count=1;$count <= $max_places;$count++){
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[$key] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
}
=========================SWAPPED CODE==============================
while($arr = $stmts->fetch()){
$array[] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
for($count=1;$count <= $max_places;$count++){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
}

You can use the built in
array_multisort()
function.
Example copied from php.net
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple")
);
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);
?>
There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
Check out https://www.php.net/manual/de/function.ksort.php (user contributes) and
https://www.php.net/manual/de/function.array-multisort.php

Use array_column() with array_search() to get the array key that needs to be modified. See the following code snippet:
<?php
// Here is trick; get the key of the array using array_column
$key = array_search('2', array_column($array, 'place'));
// If any key found modify the array
if ($key && array_key_exists($key, $array)) {
$array[$key] = [
'id' => 7,
'type' => 1,
'place' => 2,
'description' => 'This is item place 2',
'image' => 'this_is_the_image.png',
];
}
print_r($array);
See the demo

Try :
for($count=1;$count <= 3;$count++){
if(array_search($count,array_column("place",$array_from_db)) continue;
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
This will skip:
Array
(
[id] => 3
[type] => default
[place] => 2
)
=========== EDIT =============
while($arr = $stmts->fetch())
{
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
for($count=1;$count <= $max_places;$count++){
if(!isset($array[$count])){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
ksort($array);

Found the answer, thanks for all help.
Here is the trick
first we need to determine the main array like this
for($count=1;$count <= $max_places;$count++){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
Then we need to find which place is not available and show the matches.
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
$key+=1;
if($key && array_key_exists($key, $array)) {
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $res['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
The trick is in the
$key+=1;
Because the default key in array is 0.
Hope this can help others

Related

Looping and combine multiple array to one

I have an array looks like this:
Array
(
[0] => Array
(
[name] => color
[value] => red
)
[1] => Array
(
[name] => shape
[value] => square
)
[2] => Array
(
[name] => price
[value] => $15
)
)
I want to have a result like this:
$myArr = array (
'color' => 'red',
'shape' => 'square',
'price' => '$15'
)
I have tried to loop but can not get it to work.
foreach($myArr as $id => $values){
foreach ($values as $key => $value) {
if($key == 'name') {
//add to array key
} else {
//add to that array key value
}
}
}
hope you guys can help me with solution.
You can use array_column and array_combine
$arr = array(
array("name" => 'color',"value" => 'red'),
array("name" => 'shape',"value" => 'square'),
array("name" => 'price',"value" => '$15')
);
$newArr = array_combine(array_column($arr,'name'),array_column($arr,'value'));
echo "<pre>";
print_r( $newArr );
echo "</pre>";
This will result to:
Array
(
[color] => red
[shape] => square
[price] => $15
)
Doc: array_column, array_combine
$a = [
0 => [
"name" => "color",
"value" => "red",
],
1 => [
"name" => "shape",
"value" => "square",
],
2 => [
"name" => "price",
"value" => "$15",
]
];
$b = [];
foreach($a as $v)
{
$b[$v["name"]] = $v["value"];
}
var_dump($b);
result
array(3) {
["color"]=>
string(3) "red"
["shape"]=>
string(6) "square"
["price"]=>
string(3) "$15"
}
$arr = array
(
0 => array
(
'name' => 'color',
'value' => 'red'
),
1 => array
(
'name' => 'shape',
'value' => 'square'
),
2 => array
(
'name' => 'price',
'value' => '$15'
)
);
$final_array =[];
foreach($arr as $key=> $val){
$final_array[$val['name']] = $val['value'];
}
echo "<pre>"; print_r($final_array);

How to change the two-dimensional array into a one-dimensional array by my case below?

My array is like this :
$data = array(
10 => array(
"id" => 50,
"name" => 'chelsea'
),
11 => array(
"id" => 51,
"name" => 'real madrid'
)
);
I want change the array to be like this :
Array
(
[10] => 50
[11] => 51
)
I try like this :
$data = array_column($data, 'id');
But, the result like this :
Array
(
[0] => 50
[1] => 51
)
If there exist people who can solve my problem?
$data = array(
10 => array(
"id" => 50,
"name" => 'chelsea'
),
11 => array(
"id" => 51,
"name" => 'real madrid'
)
);
foreach($data as $key => $value) {
$new_data[$key] = $value['id'];
}
var_dump($new_data);
Hope it helps!
You have to declare and load a new array with the new information like so
$new_array = array();
foreach ($data as $key => $value) {
$new_array[$key] = $value['id'];
}
print_r($new_array); //display newly loaded data

insert 2 array value to new array with new key

i have below two array :
Array 1
(
[0] => Daughter
[1] => Daughter
[2] => Son
)
Array 2
(
[0] => Nitu
[1] => ritu
[2] => ramesh
)
and i want different array for each key as below :
Array(
"relation" => Daughter
"name" => Nitu
)
Array(
"relation" => Daughter
"name" => ritu
)
Array(
"relation" => Son
"name" => ramesh
)
above array 1 & array 2 can be long as per user input. so i want to insert value to new array in loop dynamically.
You simply need to loop through your array and store it in a variable $result.
Try this:
$array1 = array('Daughter', 'Daughter','Son');
$array2 = array('Nitu', 'Ritu', 'Ramesh');
foreach ($array1 as $k => $arr1) {
$result[] = array(
'relation' => $arr1,
'name' => $array2[$k]
);
}
try this,
$Aarray1 = Array
(
"0" => "Daughter",
"1" => "Daughter",
"2" => "Son"
);
$Aarray2 = Array
(
"0" => "Nitu",
"1" => "ritu",
"2" => "ramesh"
);
foreach($Aarray1 as $key=>$val)
{
$new_array[$key]["relation"] = $val;
$new_array[$key]["name"] = $Aarray2[$key];
}
DEMO
Try this :
$arrayFirst = Array("0" => "Daughter", "1" => "Daughter", "2" => "Son");
$arraySecond = Array("0" => "Nitu","1" => "ritu","2" => "ramesh");
foreach($arrayFirst as $key=>$value)
{
$new_array[$key]["relation"] = $value;
$new_array[$key]["name"] = $arraySecond[$key];
}
Probably you are trying to search for array_combine
You can check the documentation here

How to perform conditional delete in multidimensional array in PHP?

I need your help the problem description is given
The array is as follows
The given array is the sample. The main array contains many entries as follow where username can differ.
Case 1:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
1 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
Case 2:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
1 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
I want to delete the element where 'username'=>Pete and 'Option'=>no
So the output should be looks like
Array
(
[0] => Array
(
[username] => Pete
[userid] => 2
[option] => yes
)
[2] => Array
(
[username] => John
[userid] => 1
[option] => yes
)
)
All element of sub array can be same but option field either yes or no.
Please help me
Thank you very much in advance
this can be a solution
$result = array();
foreach ($yourArray as $key => $value) {
if(!($value['username']=="Pete" && $value['options']=="no"))
array_push($result, $value);
}
With this code you can achieve that:
foreach($my_array as $key => $value){
if($value['username'] == 'Pete' && $value['option'] == 'yes'){
unset($my_array[$key]);
}
}
Use a foreach loop! If the current value for username = pete add a variable user=true;
Then after that check if(option == no){ if(user==true){ DELETE ROW } }
You can use array_filter
>>> array_filter($my_array,
function($obj){
return $obj["option"] !== "no" || $obj["username"] !== "Pete";
}
)
=> [
1 => [
"username" => "Pete",
"userid" => 2,
"option" => "yes"
],
2 => [
"username" => "John",
"userid" => 1,
"option" => "no"
]
]
As the function name suggests, you should use array_filter()
$my_array = array_filter($my_array, function($v){
return ($v['username'] != 'Pete' && $v['option'] != 'no');
});

Make array unique in multidimensional array php codeigniter

I have this array
Array (
[0] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 225
[user_id] => 1
[name] => Blue Quilted Leather Jacket by Minusey - $499
)
[2] => stdClass Object
(
[id] => 222
[user_id] => 1
[name] => Darling New Bathtub by Duravit - $6300
)
)
[1] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 229
[user_id] => 1
[name] => Batman Tumbler Golf Cart - $50000
)
[2] => stdClass Object
(
[id] => 228
[user_id] => 1
[name] => Swirlio Frozen Fruit Dessert Maker - $60
)
) )
I have an array of products that I need to make sure are unique.
Need to make this array unique by id. These array are generated by pushing value.
I'm trying to solve this for more than a week now, but I dont get it to work. I know it should be easy...but anyway - I don't get it :D
Try this:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
)
);
$newArray = array();
foreach($array as $value) {
$newArray[$value['id']]['name'] = $value['name'];
$newArray[$value['id']]['id'] = $value['id'];
}
foreach($array as $key=>$inner_array)
{
foreach($array as $key_again=>$array_again)
{
if($key != $key_again)
{
if($inner_array['name'] != $array_again['name'] AND $inner_array['id'] != $array_again['id'])
{
//its okay
}
else
{
unset($array[$key]);
}
}
}
}
Not sure how the arrays are generated, but, if you can change that, you could set the array keys to the IDs directly and check if the id is already set.
Otherwise, you can do the following:
$unique = array();
foreach( $array as $values ) {
if( ! isset( $unique[$values['id']] ) ) {
$unique[$values['id']] = $values;
}
}
This will make your array unique:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
) );
$result = array();
$index = array();
foreach($array as $i => $elem) {
if(!isset($index[$elem['id']])) {
$result[$i] = $elem;
$index[$elem['id']] = 1;
}
}
echo var_export($result);
Output:
array (
0 =>
array (
'name' => 'test',
'id' => 4,
),
1 =>
array (
'name' => 'test2',
'id' => 152,
),
)
This will work. It could be considered more clean than a for loop, but I'm not sure about performance.
$array = [
[ "name" => "test", "id" => 4 ],
[ "name" => "test2", "id" => 152 ],
[ "name" => "test2", "id" => 152 ]
];
array_walk($array, function(&$item, $idx) use($array){
$matches = array_slice(array_keys($array, $item), 1);
if (in_array($idx, $matches)) {
$item = false;
}
});
$array = array_filter($array);
Edit Since you updated the data set to work with, you would need to flatten it 1 level:
$array = call_user_func_array('array_merge', $array);

Categories