adding array in PHP - 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;

Related

Create an array with indeterminate length starting on 0

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;

Search associative array of arrays. How?

My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.
Please feel free to improve on array layout.
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
Provided there will never be any duplication of the second column, you can do this:
$search = "EA_WTRESRVD"; //value to search for
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
$array = array_column($price_list, 0, 1);
echo $array[$search];
I would suggest that if you have a unique product code (SKU), you should use this to index your array.
$products = [
'EA_WTRESRVD' => [
'name' => '...',
'price' => 9.99,
// ...
],
'EA_WTRESRV' => [
'name' => '...',
'price' => 9.99,
// ...
],
];
Then you can access the price of any product by it's SKU.
$price = $products['EA_WTRESRV']['price'];
Here's one way:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
foreach ($price_list as $arr) {
if (in_array( $search, $arr )) {
echo $search;
}
}
The foreach iterates over the multidimensional array whose elements are each arrays. Each array is inspected by in_array() for the search term.
However, this is not the only way. If you wish to avoid in_array(), you could also code as follows:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
$len = strlen($search);
foreach ($price_list as $arr) {
$val = array_values($arr);
foreach($val as $v) {
if ( ( strpos( $v,$search )) !== false) {
if ( strlen($v) == $len) {
echo "$search is in the price list.\n";
}
}
}
}

adding element to array

I have an array that looks like this:
array
0 =>
array
'title' => string 'Ireland - Wikipedia, the free encyclopedia'
'url' => string 'http://en.wikipedia.org/wiki/Ireland'
1 =>
array
'title' => string 'Ireland's home for accommodation, activities.'
'url' => string 'http://www.ireland.com/'
that I want to add a score of 0 to each element. I thought this simple foreach loop would do the trick but...well....it doesn't :/
public function setScore($result)
{
foreach($result as $key)
{
$key = array('title', 'url', 'score' => 0);
}
return $result;
}
Can someone help me out?
Thanks
foreach works on a copy of the array. You can modify $key all you want, it's not going to reflect on the original array.
You can use $key by reference though, then it'll work as expected:
foreach ($result as &$value) {
$value['score'] = 0;
}
Manual entry: http://php.net/manual/en/control-structures.foreach.php
You create a new array here and do nothing with it:
foreach($result as $key){
$key = array('title', 'url', 'score' => 0);
}
What you want to do is to modify a reference to existing one:
foreach($result as &$key){ # Note the '&' here
$key['score'] = 0;
}
Although deceze is right, you can also do this using array_walk(), like this:
array_walk( $result, function( &$el) { $el['score'] = 0; });
Here's an example of how to accomplish this.
$array = array( array( 'title' => "Ireland - Wikipedia, the free encyclopedia", 'url' => "http://en.wikipedia.org/wiki/Ireland"), array( 'title' => "Ireland's home for accommodation, activities.", 'url' => "http://www.ireland.com/" ) );
function setScore( $result )
{
foreach( $result as &$element )
{
$element['score'] = 0;
}
return $result;
}
$array = setScore( $array );
print_r( $array );
You could also do:
function setScore( &$result )
{...}
and then just:
setScore( $array );

Best way to get keys and its values from an array which are not existent in another array compared only by its keys

hi I wanted to have some keys and values filtered out when compared with another array.
The "content" pair should be displayed at the end...Any help is greatly appreciated THX alot!
<?php
$test = array(
['slideid'] => 597,
['token'] =>'4e23fdd176372984870a9c65db7133b5',
['content'] =>'<p>sdg</p>',
)
$test2 = array(
['slideid'] => "",
['token'] =>""
)
foreach ($test not in $test2){
print $test2
} //not working of course
?>
This works:
$test = array(
'slideid' => 597,
'token' =>'4e23fdd176372984870a9c65db7133b5',
'content' =>'<p>sdg</p>'
);
$test2 = array(
'slideid' => "",
'token' =>""
);
foreach ($test as $key => $value){
if (!array_key_exists($key, $test2)) {
echo $value;
}
}
$arr contains the element that is in test but not test2
$arr = array_diff(array_keys($test), array_keys($test2));
print_r($arr);

PHP Api - Results/Array question

I have been looking around for PHP tutorials and I found a very detailed one that have been useful to me.
But now, I have a question. The results showed by the API are stored into a $results array. This is the code (for instance):
$fetch = mysql_fetch_row($go);
$return = Array($fetch[0],$fetch[1]);
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
My question is.. I want to display the last 10 news.. how do I do this? On normal PHP / mySQL it can be done as:
while($var = mysql_fetch_array($table)) {
echo "do something"
}
How can I make it so the $results can print multiple results?
I have tried like:
while($var = mysql_fetch_array($table)) {
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
}
But this only shows me one result. If I change the $results .= Array(...) it gives error.
What can I do?
Thanks!
Edit
My function to read it doesn't read when I put it the suggested way:
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $results);
$results[] = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
That should do it.
If you are familiar with arrays, this is the equivalent of an array_push();
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
<?php
$array[] = $var;
?>
Use [] to add elements to an array:
$results = array();
while($var = mysql_fetch_array($table)) {
$results[] = Array(
'news' => Array (
'id' => $var[0],
'title' => $var[1]
));
}
}
You can then loop through the $results array. It's not an optimal structure but you should get the hang of it with this.

Categories