Prevent adding duplicate array [duplicate] - php

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 1 year ago.
There are way to do this in JavaScript, but in PHP they don't seem to work:
$myArray = array(
array(
"name" => "John Doe",
"occupation" => "streamer"
),
array(
"name" => "Jena Doe",
"occupation" => "delivery services"
)
);
$newItem = array(
"name" => "John Doe",
"occupation" => "delivery services"
);
// now check if the name already exists
// to prevent from adding a duplicate clone of John Doe
if (!array_map(function($i){ if ($i['name'] === $newItem['name']) return true; else return false; }, $myArray)) {
$myArray[] = $newItem;
}
Why am I getting Undefined variable: $newItem and how can I do this?

You could use a simple test using in_array to see if the new array contains the duplicate name before adding?
$src = array(
array(
"name" => "John Doe",
"occupation" => "streamer"
),
array(
"name" => "Jena Doe",
"occupation" => "delivery services"
)
);
$new=array(
"name" => "John Doe",
"occupation" => "delivery services"
);
if( !in_array( $new['name'], array_values( array_column( $src, 'name' ) ) ) ){
$src[]=$new;
}

Related

PHP How to Output String from Specific Key [duplicate]

This question already has answers here:
How does true/false work in PHP?
(6 answers)
Closed 2 years ago.
I'm trying to find and output the value from a specific key.
$name = 'G';
$ids = array();
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition === false ||
$foundAtPosition > 0) {
continue;
}
$ids[] = $key['ID'];
}
echo join(',', $ids) . "\n";
Here is the array
$arrayChart = array(
array(
"Name" => "Mike G",
"ID" => "0001234",
"Hours" => 38
),
array(
"Name" => "Mike L",
"ID" => "0005678",
"Hours" => 42
)
array(
"Name" => "John G",
"ID" => "0003615",
"Hours" => 42
)
);
This code above was provided by #zedfoxus
He helped me with a previous problem.
I want to find the ID number from the key value ID by using the last name letter "G" from key Name.
I want to output them in the same line. The problem with the above function is that it doesn't print anything.
Please see the answer below.
<?php
$arrayChart = array(
array(
"Name" => "Mike G",
"ID" => "0001234",
"Hours" => 38
),
array(
"Name" => "Mike L",
"ID" => "0005678",
"Hours" => 42
),
array(
"Name" => "John G",
"ID" => "0003615",
"Hours" => 42
)
);
$name = 'G';
$ids = array();
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition) {
$ids[] = $key['ID'];
}
}
echo join(',', $ids) . "\n";
?>

Remove specific string from multidimensional array by value, not key

I need to remove Jackie Jackson from this array, I tried unset(I do not want to use key), array_diff, array_search. Nothing is working for me.
$employeeList= array(
array(
"ID" => "ID",
"Name" => "Name",
"Surname" => "Surname",
),
array(
"ID" => 1,
"Name" => "John",
"Surname" => "Smith",
),
array(
"ID" => 2,
"Name" => "Jackie",
"Surname" => "Jackson",
),
array(
"ID" => 3,
"Name" => "Chris",
"Surname" => "Jones",
),
array(
"ID" =>4,
"Name" => "Amanda",
"Surname" => "Cullen",
),
array(
"ID" =>5,
"Name" => "Jeremy",
"Surname" => "Goodwin",
),
);
if you want to unset you can use the id of Jackie Jackson to match his key.
$id = 2;
unset($employeeList[array_search($id,array_column($employeeList, "ID"))]);
Have fun :)
Array filter to check if the name and surname match. The string must contain name and surname separated by a space in this case so we can "explode" and pick up each individually. If name or surname do not exist in the "name_to_exclude" the function will simply return the original array.
$name_to_exclude = "Jackie Jackson";
$exclude = explode(' ', $name_to_exclude);
$employeeList = array_filter($employeeList, function($val) use ($exclude) {
if(array_key_exists(0, $exclude) && array_key_exists(1, $exclude)) {
return $val['Name'] != $exclude[0] && $val['Surname'] != $exclude[1];
}
return true;
});

PHP - Push data to array in foreach loop [duplicate]

This question already has answers here:
PHP Append an array to a sub array
(2 answers)
Closed 2 years ago.
I want to achieve below array format:
{
"success": true,
"results": [
{
"name" : "Choice 1",
"value" : "value1",
"text" : "Choice 1"
},
{
"name" : "Choice 2",
"value" : "value2",
"text" : "Choice 2"
}
]
}
However, I am using PHP and a foreach loop, to return some values from my database:
//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();
I then have my first part of the array, and my foreach loop:
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data_array[] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
Above only outputs:
[
{
"name":"Choice 1",
"value":"value 1",
"text":"Choice 1"
},
{
"name":"Choice 2",
"value":"value2",
"text":"Choice 2"
}
]
So it is missing the top part of my original array - but I want to loop through each database results in "results": [ ... ]
Try this
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data['results'][] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
$data['success'] = true; // if you want to update `status` as well
echo json_encode($data);
After creating $data_array array just add few lines which i have in my post.
Try this code snippet here(with sample input)
ini_set('display_errors', 1);
foreach ($showAll as $client)
{
$data_array[] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
// add these lines to your code.
$result=array();
$result["success"]=true;
$result["results"]=$data_array;
echo json_encode($result);
try this as you have an array inside the $data_array on Key "Results" so you should use "results" as a key also and then try to push data in that array
foreach ($showAll as $client) {
$data_array["results"][] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
You can simply use json_encode and push it to your result array
$data = array(
"success" => false,
"results" => array()
);
$result = [
[
"name" => "Choice 1",
"value" => "value 1",
"text" => "Choice 1"
],
[
"name" => "Choice 2",
"value" => "value2",
"text" => "Choice 2"
]
];
$data['results'] = json_encode($result);

Multi dimentional array validator [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 8 years ago.
Improve this question
I have following two arrays one array contains all valid fields and 2nd array is the data array which i want to parse.I wanted to remove any invalid fields in the data array that doesn't map with the valid field array:
Valid Fields array:
$valid_fields = array(
"first_name",
"last_name",
"uid",
"email",
"address" => array(
"mailing" => array("building_no", "street", "city", "zip", "country"),
"billing" => array("building_no", "street", "city", "zip", "country"),
"home" => array("building_no", "street", "city", "zip", "country"),
"work" => array("building_no", "street", "city", "zip", "country")
),
"home_address",
"home_address",
"billing_address",
"dob",
"gender",
"occupation",
"ip",
"site_id",
"date_created",
"social_network_ids" => array("facebook",
"twitter",
"pintreast",
"myspace",
"skype"),
"occupations" => array("current", "past" => array()),
"education", "income", "country", "city", "longitude", "latitude");
Data array:
$data = array(
"first_name" => "FFF",
"last_name" => "LLL",
"uid" => "12345", "email" => "aaa#f.com",
"address" => array(
"mailing" => array("building_no" => "BBAA", "street" => "BBSS", "city" => "BBCC")
),
"social_network_ids" => array(
"facebook" => "fbid",
"twitter" => "twitter",
),
"occupations" => array("current", "past" => array(), "yolo" => "tttt"),
);
my parsing function:
function parse_array($parms, $valid_fields) {
$result = array();
foreach ($valid_fields as $valid_field) {
if (is_array($parms[$valid_field])) {
$result[$valid_field] = parse_array($parms[$valid_field], $valid_field);
} else {
if (isset($parms[$valid_field]) && $parms[$valid_field] != "") {
$result[$valid_field] = $parms[$valid_field];
}
}
}
return $result;
}
and i call it it gives me this array which obviously not valid:
Array
(
[first_name] => FFF
[last_name] => LLL
[uid] => 12345
[email] => aaa#f.com
)
In your PHP function you're using $valid_field as an index to get the item from the $data array, but sometimes $valid_field can be an array itself, try this approach:
function parse_array($parms, $valid_fields) {
$result = array();
foreach ($valid_fields as $k => $valid_field) {
$key = $valid_field;
if (is_array($valid_field)) {
$key = $k;
}
if (isset($parms[$key])) {
if (is_array($parms[$key])) {
$result[$key] = parse_array($parms[$key], $valid_field);
} else {
if (isset($parms[$key]) && $parms[$valid_field] != "") {
$result[$key] = $parms[$valid_field];
}
}
}
}
return $result;
}

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

Categories