Blogger Information
Blog 34
fans 1
comment 0
visits 23138
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP基础4作业08-24
theYon的博客
Original
625 people have browsed it

PHP基础4
主要知识点
1)数组与字符串,变量之间的转换
2)数组元素的回调处理

代码

<?php

// 数组与字符串,变量之间的转换
$arrBook = [
    'id' => 1001,
    'type' => 'book',
    'tag' => 'php',
    'name' => 'PHP基础入门',
    'price' => '20元'
];

// 将关联数组转为变量
echo '转化为变量个数',var_export(extract($arrBook)),'<br>';
echo $price,'<br>';

// 将变量转为关联数组
$goodId = '2001';
$goodType = '电器';
$goodName = '风扇';
$arrGood = compact('goodId','goodType','goodName');
echo '<pre>';
echo var_export($arrGood),'<br>';

// 将字符串转换数组
$arrType = '家具,厨具,电器';
echo var_export(explode(',',$arrType,-1)),'<br>';

// 将数组转换字符串
$arr = ['我是','合并的','数组'];
echo var_export(implode('《》',$arr)),'<br>';

// 数组元素的回调处理
// array_filter 仅返回结果为true的元素
$arrIsNone = ['',null,'good',0,99,'wwww',false,'http'];
echo var_export($arrIsNone,true),'<br>';
$arr2 = array_filter($arrIsNone);
echo var_export($arr2,true),'<br>';

$arr3 = array_filter($arrIsNone, function ($value){
    return $value !== 'wwww';
});
echo var_export($arr3,true),'<br>';

// array_walk 对数组中每个元素的键和值进行处理
$arrBook1 = [
    'id' => 1001,
    'type' => 'book',
    'tag' => 'php',
    'name' => 'PHP基础入门',
    'price' => '20元'
];
array_walk($arrBook1,function(&$value,$key){
    echo $key,"===>",$value,"<br>";
});

array_walk($arrBook1,function(&$value,$key,$varc){
    if($key == $varc){
        exit('tag = '.$value."<br>"); 
    }
},'tag');

// 用for()循环来遍历关联数组
echo '我将遍历商品,用for方法: ',var_export($arrGood),'<br>';
for($i = 0 ; $i < count($arrGood); $i++) {
    echo '我是键:',key($arrGood),',我是值:',current($arrGood),'<br>';
    next($arrGood);
}

运行结果

TIM截图20180826174652.png

总结

     今天是知识是非常有趣的,尤其是对数组的操作,封装了好多算法,方便我们对数组的查询,而后是for 与 foreach

for 既需要计算数组长度又需要一个自增变量,来指向下一数组元素。而foreach直接对该数组循环,能过直接获取键值对,自动指向下一元素。是十分有用的语句

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post