Create an array with indeterminate length starting on 0 - php

I have 50 (or less) arrays from database and I need to return them in one array.
I'm currently using
$results = DB::table('coinflip_history')->where('ct', Auth::user()->steamid)->orWhere('t', Auth::user()->steamid)->orderByRaw('round_id DESC')->limit(50)->get();
$results = json_decode($results, true);
$i=1;
foreach ($results as $key => $value) {
if (!$value['winner']) $array[$i] = array('secret' => null, 'winning_string' => null, 'hash' => $value['hash'], 'timestamp' => $value['time']);
else $array[$i] = array('secret' => $value['secret'], 'winning_string' => $value['percentage'], 'hash' => $value['hash'], 'timestamp' => $value['time']);
$i++;
}
return array($array[1], $array[2], $array[3], $array[4], $array[5], $array[6], $array[7], $array[8], $array[9], $array[10], $array[11], $array[12], $array[13], $array[14], $array[15], $array[16], $array[17], $array[18], $array[19], $array[20], $array[21], $array[22], $array[23], $array[24], $array[25], $array[26], $array[27], $array[28], $array[29], $array[30], $array[31], $array[32], $array[33], $array[34], $array[35], $array[36], $array[37], $array[38], $array[39], $array[40], $array[41], $array[42], $array[43], $array[44], $array[45], $array[46], $array[47], $array[48], $array[49], $array[50]);
But if there are less than 50 arrays it's not working.
Is there any way to make it work automatically?

All arrays have indices.
It's just that kind of data data structure.
There is no way on PHP of generating an array without indices. It wouldn't be an array.
The only thing you are accomplishing with your code is generating an array starting on 1, and then creating a new array starting on 0.
Since both things are functionally equivalent, I guess that the problem exist down the line when you return an 1-based array.
So if you would do:
$array = [];
$results = json_decode($results, true);
foreach($results as $key => $value){
if(!$value['winner']) {
$array[] = [
'secret' => null,
'winning_string' => null,
'hash' => $value['hash'],
'timestamp' => $value['time']
];
}
else {
$array[] = [
'secret' => $value['secret'],
'winning_string' => $value['percentage'],
'hash' => $value['hash'],
'timestamp' => $value['time']
];
}
}
return $array;
You'd get what you need. This is 100% the same than what you are doing up there, but with less steps, and that works for any number of values on the returned $array.

// as simple as this
return $array;

Related

How to remove a array from an array by comparing it with another array?

I've 2 array as below. One array is a 2 dimensional array($array_1) and another is a simple array ($array_2). This $array_1 as a key called private_name in each array and $array_2 has a list of private_key values. I want to keep the array from $array_1 which matches with $array_2.
$array_1 = [
[0] => ['id'=>12, 'private_name' => 'name12', 'age' => '23'],
[1] => ['id'=>2, 'private_name' => 'name2', 'age' => '23'],
[2] => ['id'=>9, 'private_name' => 'name1', 'age' => '23'],
[3] => ['id'=>11, 'private_name' => 'name11', 'age' => '23'],
.
.
.
[999] => ['id'=>999, 'private_name' => 'name999', 'age' => '23'],
];
$array_2 = ['name1', 'name2', 'name3',....];
So i wante remove array contents from $array_1 which matches with $array_2. Currently am using the below method but it takes a lot of time as there are 14k+ array values in $array_1. Is there any soulution for this which just uses 1 line to solve the above. I want a solution like
$newVal = array_intersect(array_column($array_1, 'private_name'), $array_2);
Current am doing like below which takes a lot of time
$results = array();
$count = 0;
if (count($array_1) > 0) {
foreach ($array_1 as $row) {
foreach ($row as $col => $val) {
foreach ($array_2 as $key3 => $pvt_name) {
if (strcmp($row['private_name'], $array_1) == 0) {
$results[$count][$col] = $val;
}
}
}
$count++;
}
}
Any help is much appreciated. Thank you
This can easily be done using array_filter.
$filtered_array = array_filter($array_1, function($item) use($array_2) {
return !in_array($item['private_name'], $array_2);
});
var_dump($filtered_array);
The callback function needs to return true to keep the item in the result, false to discard it. That is done here by checking if the private_name value of the item is contained in your second array - and the result of that negated, because you only want to keep those that don’t match.

Loop over one array as if it was a multidimensional array

I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);

Transform array to assosiative array in PHP

I want to change my $data format, so that it matches $x's format
$x = [
'021' => [
'province' => 'jatim',
'city' => 'surabaya'
],
'031' => [
'province' => 'jabar',
'city' => 'jakarta'
]
];
$data = [
['031', 'jatim', 'surabaya'],
['021', 'jabar', 'jakarta']
];
Use foreach loops to iterate through your array.
$x = [];
foreach( $data as $d )
{
$x[$d[0]] = ["province"=>$d[1],"city"=>$d[2]];
}
$d[0] represents the initial string ID.
$d[1] represents the province.
$d[2] represents the city.
$result= array();
foreach ($data as $value) {
$result[$value[0]] = array('province'=>$value[1],'city'=>$value[2]);
}
Explanation:
Create resulting array. Fetch through provided array to insert data in resulting array. If needed unset data array if no longer needed.

adding array in PHP

First, im new in PHP so please bear with me.
I just want to add an array with the foreach loop but I can't.
if($size > 0)
{
$resultArray = array();
foreach($result as $hospital)
{
if($hospital)
{
$temp = array('result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']);
$resultArray = array_merge_recursive($resultArray, $temp);
//$resultArray = array_splice($resultArray, $i, 0, $temp);
}
}
$this->response($resultArray, 200);
}
I tried to create a $temp array and merge it to the final result, and finally print that final result ($resultArray) to the response.
The array is successfully merged, but not in the way i want. This is the JSON result :
{"result":["true","true"],"total":[2,2],"id":["1","2"],"name":["test","keyword"],"address":["alamat test","alamat keyword"],"telp":["123456","789"]}
What i want is something like this :
-0 :{
result: "true"
total: 2
id: "1"
name: "test"
address: "alamat test"
telp: "123456"
}
-1 :{
result: "true"
total: 2
id: "2"
name: "test2"
address: "alamat tes 2t"
telp: "789"
}
So the response should be an array with 2 items, and each items has some items.
Please kindly help me, Thanks for your help.
It looks to me like you're trying to append an array, to an array, which can be done quite easily:
$resultArray = array();//outside the loop
//loop
$resultArray[] = array(
'result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']
);
Job done. You could also use the array_push function, but that's a function. Functions equal overhead, and should, therefore be avoided (if it doesn't affect code readability). You use array_merge and array_merge_recursive if you want to combine arrays:
$foo = array(
array('bar' => 'zar')
);
$bar = array(
array('car' => 'far')
);
var_dump(
array_merge(
$foo,
$bar
)
);
The effect of array_merge here is comparable to:
foreach ($bar as $subArray)
$foo[] = $subArray;
Im not totally sure how you want your final array to be, but this will put it like $resultArray[0] = array( //temparray ) etc..:
if($size > 0){
$resultArray = array();
$i=0;
foreach($result as $hospital){
if($hospital){
$temp = array('result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']);
$resultArray[$i][$temp];
$i++;
}
}
$this->response($resultArray, 200);
}
Replace this -
$resultArray = array_merge_recursive($resultArray, $temp);
With this -
$resultArray[] = $temp;

php remove object from array of objects

I'm trying to remove an object from an array of objects by its' index. Here's what I've got so far, but i'm stumped.
$index = 2;
$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'),
1=>array('label'=>'bar', 'value'=>'2n13'),
2=>array('label'=>'foobar', 'value'=>'n2314'),
3=>array('label'=>'barfoo', 'value'=>'03n23')
);
//I've tried the following but it removes the entire array.
foreach ($objectarray as $key => $object) {
if ($key == $index) {
array_splice($object, $key, 1);
//unset($object[$key]); also removes entire array.
}
}
Any help would be appreciated.
Updated Solution
array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters
//(array, start, length) removes the given array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
array_splice($objectarray, $index, 1);
//array_splice accepts 3 parameters (array, start, length) and removes the given
//array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
You have to use the function unset on your array.
So its like that:
<?php
$index = 2;
$objectarray = array(
0 => array('label' => 'foo', 'value' => 'n23'),
1 => array('label' => 'bar', 'value' => '2n13'),
2 => array('label' => 'foobar', 'value' => 'n2314'),
3 => array('label' => 'barfoo', 'value' => '03n23')
);
var_dump($objectarray);
foreach ($objectarray as $key => $object) {
if ($key == $index) {
unset($objectarray[$index]);
}
}
var_dump($objectarray);
?>
Remember, your array will have odd indexes after that and you must (if you want) reindex it.
$foo2 = array_values($objectarray);
in that case you won't need that foreach just unset directly
unset($objectarray[$index]);

Categories